Skip to content

Instantly share code, notes, and snippets.

@jt000
Created March 10, 2017 23:21
Show Gist options
  • Save jt000/eef096a2341471856e8a86d06aaec887 to your computer and use it in GitHub Desktop.
Save jt000/eef096a2341471856e8a86d06aaec887 to your computer and use it in GitHub Desktop.
public class ServiceProviderControllerActivator : IHttpControllerActivator
{
private readonly IHttpControllerActivator _parent;
private readonly IServiceProvider _provider;
public ServiceProviderControllerActivator(IHttpControllerActivator parent, IServiceProvider provider)
{
_parent = parent;
_provider = provider;
}
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
var scope = _provider.CreateScope();
request.RegisterForDispose(scope);
var controller = scope.ServiceProvider.GetService(controllerType) as IHttpController;
if (controller == null && _parent != null)
{
controller = _parent.Create(request, controllerDescriptor, controllerType);
}
return controller;
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
var services = new ServiceCollection();
/* Add Services & Controllers */
var provider = services.BuildServiceProvider();
var config = new HttpConfiguration();
var parentActivator = config.Services.GetService(typeof (IHttpControllerActivator)) as IHttpControllerActivator;
config.Services.Replace(typeof (IHttpControllerActivator), new ServiceProviderControllerActivator(parentActivator, provider));
app.UseWebApi(config);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment