I'm beginner in asp.net mvc. I have a qusetion and I believe that anybody help me on stackoverflow) I can't understand for what using IoC and DI in ASP.NET MVC. Can you help me. Maybe i'm stupid but I really want to know it) Ccan someone explain clearly? I would be very grateful.
-
take a look at this. http://www.dotnet-tricks.com/Tutorial/dependencyinjection/bSVa100413-Understanding-Inversion-of-Control,-Dependency-Injection-and-Service-Locator.html – Tan Feb 18 '14 at 08:15
1 Answers
For ASP.NET MVC in particular, controllers have a lot of dependencies that DI and an IoC container can decouple through interfaces to make them mockable for unit testing, also easier to change over time without impacting the controllers.
For example, if a controller relies on a logging provider, a custom configuration provider, and a domain service or two (which themselves rely on data managers and likely other dependencies), how to unit test the controller - with so many external dependencies?
The way to accomplish this is to make its dependencies injectable (i.e. DI) and the injected dependencies to use a matter of configuration (i.e. an IoC container).
Consider the following constructor...
public MyController()
{
_logger = new Logger();
_configProvider = new ConfigProvider();
_customerService = new CustomerService();
_orderService = new OrderService();
}
...versus...
public MyController(ILogger logger, IConfigProvider configProvider, ICustomerService customerService, IOrderService orderService)
{
_logger = logger;
_configProvider = configProvider;
_customerService = customerService;
_orderService = orderService;
}
..., which allows for injecting dependencies (e.g. mocks in unit tests), which can be configuration-driven using an IoC container.
The difference is night-and-day from a testability and maintainability perspective.

- 8,740
- 10
- 53
- 80