Last active
November 21, 2023 12:45
-
-
Save jt000/0b57f811807d119090f1184bb3460dee to your computer and use it in GitHub Desktop.
Using Microsoft.Extensions.DependencyInjection in WebAPI 2
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
using System; | |
using System.Net.Http; | |
using System.Web.Http.Controllers; | |
using System.Web.Http.Dispatcher; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace Web | |
{ | |
public class ServiceProviderControllerActivator : IHttpControllerActivator | |
{ | |
private readonly IServiceProvider _provider; | |
public ServiceProviderControllerActivator(IServiceProvider provider) | |
{ | |
_provider = provider; | |
} | |
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) | |
{ | |
var scopeFactory = _provider.GetRequiredService<IServiceScopeFactory>(); | |
var scope = scopeFactory.CreateScope(); | |
request.RegisterForDispose(scope); | |
return scope.ServiceProvider.GetService(controllerType) as IHttpController; | |
} | |
} | |
} |
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
using System.Web.Http; | |
using System.Web.Http.Dispatcher; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace Web | |
{ | |
public static class WebApiConfig | |
{ | |
public static void Register(HttpConfiguration config) | |
{ | |
// Web API configuration and services | |
var services = new ServiceCollection(); | |
InitializeServices(services); | |
var provider = services.BuildServiceProvider(); | |
config.Services.Replace(typeof(IHttpControllerActivator), new ServiceProviderControllerActivator(provider)); | |
// Web API routes | |
config.MapHttpAttributeRoutes(); | |
config.Routes.MapHttpRoute( | |
name: "DefaultApi", | |
routeTemplate: "api/v1.0/{controller}" | |
); | |
} | |
public static void InitializeServices(IServiceCollection services) | |
{ | |
// Add whatever services you want... | |
services.AddYOURService(); | |
// Add your controllers (can probably find a dynamic way to do this) | |
services.AddScoped<YOURController>(sp => new YOURController(sp.GetRequiredService<YOURService>())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you have a solution for injecting into ActionFilters too?