ebb
ebb

Reputation: 9377

MVC3 Controller constructor + Ninject

I'm at the moment working on a MVC3 Web application and ecountered a new problem with Ninject.

I'm using the following code in my controller:

public class TestController : Controller
{       
    public IRepository<CustomerModel> rep;

    public TestController(IRepository<CustomerModel> repository)
    {
        this.rep = repository;
    }

    public ActionResult Index()
    {
        return View();
    }
}

And my Ninject Module:

public class RepositoryModule : NinjectModule
{
    public override void Load()
    {
        Bind(typeof(IRepository<>)).To(typeof(Repository<>));
    }
}

However this just throws me "System.MissingMethodException: No parameterless constructor defined for this object." when I try to render the Index view.

If I then add:

public TestController() : this(new Repository<CustomerModel>(new XenCRMEntities())) { }

so my actually TestController looks like:

public class TestController : Controller
{       
    public IRepository<CustomerModel> rep;

    public TestController() : this(new Repository<CustomerModel>(new XenCRMEntities())) { }

    public TestController(IRepository<CustomerModel> repository)
    {
        this.rep = repository;
    }

    public ActionResult Index()
    {
        return View();
    }
}

It works, but as you can see the new constructor pretty much break the whole point of IoC.

How do I fix this?

Thanks in advance.

Upvotes: 3

Views: 11783

Answers (4)

qBufff
qBufff

Reputation: 11

Don't use this binding!!!

Bind(typeof(IRepository<>)).To(typeof(Repository<>));

I changed my code use this binding and server was crashed, it works for one user but for thousands requests it's really bad

Use

Bind(typeof(IRepository<IClass>)).To(typeof(Repository<Class>))

Upvotes: 0

Remo Gloor
Remo Gloor

Reputation: 32725

A short test showed that there is not problem with generic bindings in the MVC3 extension. I guess that the problem is not in the Controller but that the Repository can not be created because it has some unknown dependencies.

But this brought me to change the dependency resolver a bit to show the Ninject stacktrace whenever the requested type can be resolved but one of its dependencies fails to be resolved. Update to the latest version on the build server to get a better stack trace.

Upvotes: 4

ebb
ebb

Reputation: 9377

It turns out that its not the Controller thats messing it up, but that Ninject dont Bind my generic Repository and IRepository correctly - I have therefore created a new post: Ninject + Bind generic repository

Upvotes: 2

CGK
CGK

Reputation: 2662

You will need to change the controller factory, as the regular MVC controller factory does not do DI.

You can look here for more information on how to setup MVC + Ninject: MVC3 + Ninject - How to?

Upvotes: 2

Related Questions