Update: There's an official Autofac OWIN nuget package and a page with some docs.
Original:
There's a project that solves the problem of IoC and OWIN integration called DotNetDoodle.Owin.Dependencies available through NuGet. Basically Owin.Dependencies
is an IoC container adapter into OWIN pipeline.
Sample startup code looks like:
public class Startup
{
public void Configuration(IAppBuilder app)
{
IContainer container = RegisterServices();
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute("DefaultHttpRoute", "api/{controller}");
app.UseAutofacContainer(container)
.Use<RandomTextMiddleware>()
.UseWebApiWithContainer(config);
}
public IContainer RegisterServices()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterOwinApplicationContainer();
builder.RegisterType<Repository>()
.As<IRepository>()
.InstancePerLifetimeScope();
return builder.Build();
}
}
Where RandomTextMiddleware
is implementation of OwinMiddleware
class from Microsoft.Owin.
"The Invoke method of the OwinMiddleware class will be invoked on each request and we can decide there whether to handle the request, pass the request to the next middleware or do the both. The Invoke method gets an IOwinContext instance and we can get to the per-request dependency scope through the IOwinContext instance."
Sample code of RandomTextMiddleware
looks like:
public class RandomTextMiddleware : OwinMiddleware
{
public RandomTextMiddleware(OwinMiddleware next)
: base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
IServiceProvider requestContainer = context.Environment.GetRequestContainer();
IRepository repository = requestContainer.GetService(typeof(IRepository)) as IRepository;
if (context.Request.Path == "/random")
{
await context.Response.WriteAsync(repository.GetRandomText());
}
else
{
context.Response.Headers.Add("X-Random-Sentence", new[] { repository.GetRandomText() });
await Next.Invoke(context);
}
}
}
For more information take a look at the original article.