Skip to content

Instantly share code, notes, and snippets.

@wilwang
Last active October 29, 2015 18:16
Show Gist options
  • Save wilwang/91f4f7d7667ffd7f55a2 to your computer and use it in GitHub Desktop.
Save wilwang/91f4f7d7667ffd7f55a2 to your computer and use it in GitHub Desktop.
WebApi Controller Dependency Injection using Unity Container
// I'm not sure if this is the best or most correct way to do it, but it seems to work in my prototype.
// Basically, I want "dependency injection" for my controller, and after reading some tech blogs online,
// it seems like the best way to do this is to use IHttpControllerActivator to inject dependencies into
// your controller because you will have context of the request doing it this way as opposed to doing it
// via traditional dependency injection.
// this code in Global.asax.cs
public WebApiApplication()
{
this.container = new UnityContainer();
container.RegisterType<IMyRepository, MyRepository>(new HierarchicalLifetimeManager());
container.RegisterType<IModelFactory<dbModel, dto>, MyDtoFactory>(new HierarchicalLifetimeManager());
}
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator),
new UnityControllerFactory(this.container));
}
// UnityControllerFactory to do injection
public class UnityControllerFactory : IHttpControllerActivator
{
private readonly IUnityContainer container;
public UnityControllerFactory(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
IUnityContainer childContainer = this.container.CreateChildContainer();
var controller = (IHttpController)childContainer.Resolve(controllerType);
request.RegisterForDispose(new Release(() => childContainer.Dispose()));
return controller;
}
}
internal class Release: IDisposable
{
private readonly Action release;
public Release(Action release)
{
this.release = release;
}
public void Dispose()
{
this.release();
}
}
// my controller
public FundsController(IMyRepository repository, IModelFactory<dbModel, dto> factory)
{
this.repository = repository;
this.factory = factory;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment