in Startup.cs
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
var controllerActivator = new CompositionRoot();
services.AddSingleton<IControllerActivator>(controllerActivator);
}
CompositionRoot.cs
public class CompositionRoot : IControllerActivator, IDisposable
{
// Singletons
private readonly ISingleton _singleton;
public CompositionRoot()
{
// Create singletons
_singleton = new Singleton();
}
public object Create(ControllerContext c) => this.Create(c.ActionDescriptor.ControllerTypeInfo.AsType());
public void Release(ControllerContext c, object controller) => (controller as IDisposable)?.Dispose();
public Controller Create(Type type)
{
// scoped
var scoped = new Scoped();
// transient get new()-ed up below
if (type == typeof(HomeController))
return new HomeController(_singleton, scoped, new Transient());
throw new InvalidOperationException($"Unknown controller {type}.");
}
public void Dispose()
{
// dispose stuff
}
}