Example
public interface ISingleton : IDisposable { }
public class TransientDependency { }
public class Singleton : ISingleton
{
public void Dispose() { }
}
public class CompositionRoot : IDisposable, IHttpControllerActivator
{
private readonly ISingleton _singleton;
// pass in any true singletons i.e. cross application instance singletons
public CompositionRoot()
{
// intitialise any application instance singletons
_singleton = new Singleton();
}
public void Dispose()
{
_singleton.Dispose();
}
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
// Per-Request-scoped services are declared and initialized here
if (controllerType == typeof(SomeApiController))
{
// Transient services are created and directly injected here
return new SomeApiController(_singleton, new TransientDependency());
}
var argumentException = new ArgumentException(@"Unexpected controller type! " + controllerType.Name,
nameof(controllerType));
Log.Error(argumentException, "don't know how to instantiate API controller: {controllerType}", controllerType.Name);
throw argumentException;
}
}
public static class DependencyInjection
{
public static void WireUp()
{
var compositionRoot = new CompositionRoot();
System.Web.Http.GlobalConfiguration.Configuration.Services.Replace(typeof (IHttpControllerActivator), compositionRoot);
}
}