Alex Rivera | Logout

what's the point of Dependency Injection Frameworks?

Asked 2010-08-12T03:56:23.593
9

I am sure that I am somewhat lost in this area... my understanding is that Dependency Injection means initializing something that is required by a class..so for instance. If my controller is going to need a service and I want to be able to test it then I should define two Constructor methods for it... so, my question is... why do people use Frameworks to achieve this?? Im lost

public class CompaniesController : Controller
    { 
        private ICompaniesService _service;

        public CompaniesController()
        {
            _service = new CompaniesService();
        }

        public CompaniesController(ICompaniesService service)
        {
            _service = service;
        }
Edit
Report

2 Answers

6

A major reason is to better support unit testing and mocking out objects to create controlled tests.

By not specifying the implementation inside the class, you can 'inject' an implementation at run time. (In your example, the ICompaniesService interface).

At runtime, using an inversion of control/dependency injection container such as StructureMap, Unity or Castle Windsor, you can say "hey, anytime someone wants an instance of ICompaniesService give them a new CompaniesService object".

To unit test this class, you can mock our a ICompaniesService and supply it yourself to the constructor. This allows you to setup controlled methods on the mock object. If you couldn't do this, your unit tests for CompaniesController would be limited to using only the one implementation of your companies service, which could hit a live database etc, making your unit tests both slow and inconsistent.

answered 2010-08-12T04:02:14.737
1

From Wikipedia:

Without the concept of dependency injection, a consumer who needs a particular service "ICompaniesService" in order to accomplish a certain task would be responsible for handling the life-cycle (instantiating, opening and closing streams, disposing, etc.) of that service. Using the concept of dependency injection, however, the life-cycle of a service is handled by a dependency provider/framework (typically a container) rather than the consumer. The consumer would thus only need a reference to an implementation of the service "ICompaniesService" that it needed in order to accomplish the necessary task.

Read this one too:

What is dependency injection?

answered 2010-08-12T04:03:56.293

Your Answer