ChevCast
ChevCast

Reputation: 59213

How to do ASP.NET Dependency Injection

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.

Upvotes: 1

Views: 1937

Answers (2)

Winger
Winger

Reputation: 676

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; }
    }
}

Upvotes: 4

Afshin Gh
Afshin Gh

Reputation: 8198

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.

Upvotes: 0

Related Questions