Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Microsoft.Extensions.DependencyInjection with OWIN Self-Hosted WebAPI
// ...
using Microsoft.Owin.Hosting;
// ...
public class ServiceHost
{
private IDisposable server = null;
const string baseAddress = "https://*:443";
public void Start()
{
server = WebApp.Start<WebApiStartup>(baseAddress);
}
public class WebApiStartup
{
public void Configuration(IAppBuilder appBuilder)
{
appBuilder.Map("/api", api =>
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
// Add IoC
var serviceProvider = IocStartup.BuildServiceProvider();
config.DependencyResolver = new DefaultDependencyResolver(serviceProvider);
// ...
api.UseCors(CorsOptions.AllowAll);
api.UseWebApi(config);
});
// ...
// ...
using System.Web.Http.Dependencies;
using Microsoft.Extensions.DependencyInjection;
// ...
public class DefaultDependencyResolver : IDependencyResolver
{
private readonly IServiceProvider provider;
public DefaultDependencyResolver(IServiceProvider provider)
{
this.provider = provider;
}
public object GetService(Type serviceType)
{
return provider.GetService(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return provider.GetServices(serviceType);
}
public IDependencyScope BeginScope()
{
return this;
}
public void Dispose()
{
}
}
public static class IocStartup
{
public static IServiceProvider BuildServiceProvider()
{
var services = new ServiceCollection();
// Register all dependent services
//
// IocSomeAssembly.Register(services);
//
// services.AddTransient<ISomething, Something>()
// For WebApi controllers, you may want to have a bit of reflection
var controllerTypes = Assembly.GetExecutingAssembly().GetExportedTypes()
.Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
.Where(t => typeof(ApiController).IsAssignableFrom(t)
|| t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase));
foreach (var type in controllerTypes)
{
services.AddTransient(type);
}
// It is only that you need to get service provider in the end
var serviceProvider = services.BuildServiceProvider();
return serviceProvider;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment