Dependency Injection Frameworks

Unity

“The Unity Container (Unity) is a lightweight, extensible dependency injection container. It facilitates building loosely coupled applications”

This was very simple to setup for an ASP.NET MVC project (net461) using the nuget packages:

  •  Unity.Container, Version=5.7.0
  •  Unity.Abstractions, Version=3.3.0
  •  Unity.Mvc, Version=5.0.13

Implementation is as simple as this:

~ /App_Start/UnityConfig.cs
public static void RegisterComponents()
{
     var container = new UnityContainer();
     container.RegisterType<IClientRepository, ClientRepository>();
     DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

~/Global.asax.cs
UnityConfig.RegisterComponents();

~/Controllers/KiefController.cs
Constructor signature can then include `IClientRepository clientRepository`

Autofac

Uses an IOC (Inversion of control) container. This was useful in a legacy Web Forms application (Autofac, Version=4.8.1.0) however it would have worked just as well in the MVC application I used Unity in.

~ /Modules/ApplicationModule.cs
protected override void Load(ContainerBuilder builder)
{
   builder.Register(db => new NpgsqlConnectionFactory(ConnectionName)).As<IDatabaseConnectionFactory>();
   
   //default ctr
   builder.Register(cm => new ClientRepository()).As<IClientRepository>();

   //ctr with connection param
   builder.RegisterType<ClientRepository>()
   .As<IClientRepository>()
   .WithParameter(ConnectionName, new NpgsqlConnectionFactory(ConnectionName));
}
~ Build
var container = builder.Build();

~ Resolve
var clientRepository = container.Resolve<IClientRepository>();

Others

  • Structure Map
  • Windsor

Leave a Reply