Skip to content

Instantly share code, notes, and snippets.

@jt000
Last active November 21, 2023 12:45
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jt000/0b57f811807d119090f1184bb3460dee to your computer and use it in GitHub Desktop.
Save jt000/0b57f811807d119090f1184bb3460dee to your computer and use it in GitHub Desktop.
Using Microsoft.Extensions.DependencyInjection in WebAPI 2
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;
}
}
}
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>()));
}
}
}
@Palpie
Copy link

Palpie commented May 16, 2018

Do you have a solution for injecting into ActionFilters too?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment