Created
March 10, 2017 23:21
-
-
Save jt000/eef096a2341471856e8a86d06aaec887 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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