Search code examples
asp.net-mvc-3dependency-injectionninjectfactory-pattern

Ninject MVC 3 - Injecting dependencies into models and controllers


I don't fully understand what's happening behind the scenes when we inject dependencies into controllers and models.

I have the following controller:

    public class TypeController : CommonController
    {
        private ILookUpService lookUpService;

        public TypeController(ILookUpService lookUpService)
        {
            this.lookUpService = lookUpService;    
        }   

    }

As the application starts, the lookup service is already available. So I guess that somewhere behind scenes we have code on the lines of

TypeController controller = new TypeController(service);

or something to do with factory (which I need to read up about).

When it comes to injecting a service into a view model, it doesn't work as I need to invoke an empty constructor without passing interface to my service.

So what is happening behind the scenes? How do I inject a service into a view model? I guess I'm missing some real fundamental stuff which is stopping me from doing what I need.

I have included FactoryPattern in the tags as my gut feeling tell me it has something to do with my problem..

Thank you


Solution

  • You shouldn't inject anything into the view model. The view model should be a simple data container which is filled from the controller and therefore shouldn't have any dependencies.