So on a high level I understand the concept of dependency injection. Our company wants to adopt this practice and I think it is a good idea, but I need some more information and have a few questions.
What is a good or most popular dependency injection container? I have heard of ninject, does that work well with .NET 4 Webforms? Does Microsoft have a proprietary DI Container that might be better?
Our application structure is like this:
- Solution
- UI Project (ASP.NET Web App)
- Business Layer (Class Library)
- Data Access Layer (Class Library)
- The data access layer contains repository classes for accessing data. These repositories sit under interfaces that the business layer interacts with.
- The business layer has "controller" classes (not to be confused with MVC controllers) that contain common functionality.
- Solution
Here is an example controller from our business layer:
public class OrderController
{
IOrderRepository _orderRepository;
public OrderController(IOrderRepository orderRepository)
{
_orderRepository = orderRepository;
}
public List<string> GetFilters()
{
// Return list of filters.
}
public List<Order> GetFilteredOrders(string filter)
{
switch (filter)
{
case "Newest":
return // Get orders sorted by newest first.
case "Oldest":
return // Get orders sorted by oldest first.
default:
return // etc etc etc
}
}
}
As you can see this takes an injected instance of IOrderRepository
for easy unit testability. OrderController
is currently instantiated in the code behind of the appropriate page that needs to use it. We don't want to create a new IOrderRepository
in every place where we instantiate OrderController
, this is where we want to use DI.
What is the best way to implement this? At what point does the DI Container take over and inject an instance of IOrderRepository
? Would there be some kind of factory so I could do OrderController _orderController = OrderControllerFactory.Create()
or something like that? I'm kind of lost.
Let me know if I need to clarify something. Thank you.