Does the simple IOC MVC 4 injector support ASP.NET Web API?
It does not currently support the MVC4 web API, but support will be added in the future. The integration guide will be updated when this happens.
UPDATE : Web API support added in Simple Injector 2.5.
In the meantime, you can create your own implementation of System.Web.Http.Dependencies.IDependencyResolver for a simple injector. The following is an implementation for working with the web API in the IIS hosting environment:
public class SimpleInjectorHttpDependencyResolver : System.Web.Http.Dependencies.IDependencyResolver { private readonly Container container; public SimpleInjectorHttpDependencyResolver( Container container) { this.container = container; } public System.Web.Http.Dependencies.IDependencyScope BeginScope() { return this; } public object GetService(Type serviceType) { IServiceProvider provider = this.container; return provider.GetService(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { IServiceProvider provider = this.container; Type collectionType = typeof(IEnumerable<>).MakeGenericType(serviceType); var services =(IEnumerable<object>)this.ServiceProvider.GetService(collectionType); return services ?? Enumerable.Empty<object>(); } public void Dispose() { } }
This implementation does not use scope, since you need to use the Per Web Api Request to implement the scope within the web host (where the request may end in a different thread than where it was launched).
Due to the way the Web API is designed , it is very important to explicitly register all web API controllers. You can do this using the following code:
var services = GlobalConfiguration.Configuration.Services; var controllerTypes = services.GetHttpControllerTypeResolver() .GetControllerTypes(services.GetAssembliesResolver()); foreach (var controllerType in controllerTypes) { container.Register(controllerType); }
You can register SimpleInjectorHttpDependencyResolver as follows:
Steven Jun 29 2018-12-12T00: 00Z
source share