1

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.

  1. 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?

  2. 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.

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.

CatDadCode
  • 58,507
  • 61
  • 212
  • 318

2 Answers2

4

My preference is to stick with the Microsoft stack and use Unity; although I have colleagues who use Ninject on projects and love it.

Here is how I do this exact thing in a web application (MVC apps are just slightly more involved):

using Microsoft.Practices.Unity;

public class OrderController
{
    IOrderRepository _orderRepository;

    [InjectionConstructor]
    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
        }
    }
}


/// 
/// From Global.asax.cs

using Microsoft.Practices.Unity;

private void ConfigureUnity()
{        
    // Create UnityContainer           
    IUnityContainer container = new UnityContainer()
    .RegisterInstance(new OrderController())
    .RegisterType<IOrderRepository, OrderRepository>();

    // Set container for use in Web Forms
    WebUnityContainer.Container = container;
}       

///
/// Creating the OrderController from your Web UI

public OrderController CreateOrderController()
{
    return WebUnityContainer.Container.Resolve<OrderController>();
}

///
/// Shared static class for the Unity container

using Microsoft.Practices.Unity;

namespace MyCompany.MyApplication.Web
{
    public static class WebUnityContainer
    {
        public static IUnityContainer Container { get; set; }
    }
}
Winger
  • 676
  • 3
  • 7
  • Could you clarify the latter half of the code you included? So the `ConfigureUnity()` method goes in global.asax.cs, where does `CreateOrderController()` and `WebUnityContainer` go? Where does `ConfigureUnity()` get called? Also, `.RegisterInstance(new OrderController())` won't compile because OrderController does not have a constructor that takes zero arguments. – CatDadCode Apr 07 '11 at 21:59
  • The WebUnityContainer class could be added to your business module since both the web classes and your domain classes will need access. ConfigureUnity() is called in Global.asax.cs inside your Application_Start() method. – Winger Apr 07 '11 at 22:10
  • 1
    Oops, my bad. Try registering the OrderController like this: .RegisterType(), when you call Resolve() on the UnityContainer it creates the object using the constructor with the most arguments and resolves your dependencies for each interface passed to that constructor. – Winger Apr 07 '11 at 22:12
0

Using Structure Map here.

http://structuremap.net/structuremap/

In Structure Map it's like this:

ObjectFactory.GetInstance(Of OrderController)

Nice links about Structure Map:

http://weblogs.asp.net/shijuvarghese/archive/2008/10/10/asp-net-mvc-tip-dependency-injection-with-structuremap.aspx

Which .NET Dependency Injection frameworks are worth looking into?

Open source app:

Uses Unity, another good dependency injection framework: http://kigg.codeplex.com/

I had the same question 1~2 years ago, and I have been using StructureMap since then and I'm happy with it but I know other frameworks like Ninject are as good as StructureMap.

Community
  • 1
  • 1
Afshin Gh
  • 7,918
  • 2
  • 26
  • 43