Skip to content

Instantly share code, notes, and snippets.

@randomcodenz
Created November 3, 2014 19:30
Show Gist options
  • Save randomcodenz/9d2c83ba9f826a382e91 to your computer and use it in GitHub Desktop.
Save randomcodenz/9d2c83ba9f826a382e91 to your computer and use it in GitHub Desktop.
Autofac aware OWIN middleware - trying to inject the equivalent of IDependencyResolver into any middleware that needs it
public class AutofacAppBuilder : IAppBuilder
{
private readonly IAppBuilder _inner;
private readonly IContainer _container;
public AutofacAppBuilder( IAppBuilder inner, IContainer container )
{
_inner = inner;
_container = container;
}
public IDictionary<string, object> Properties { get { return _inner.Properties; } }
public IAppBuilder New()
{
return new AutofacAppBuilder( _inner.New(), _container );
}
public IAppBuilder Use( object middleware, params object[] args )
{
// Wrap the middleware + args into something resembling AutofacMiddleware and then:
// _inner.Use( wrappedMiddleware );
// Autofac middleware will have to be smart enough to handle bypassing middleware that should not be
// intercepted. This is the hard part of the problem :)
return this;
}
public object Build( Type returnType )
{
return _inner.Build( returnType );
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
var container = InitialiseContainer();
var autofacApp = new AutofacAppBuilder( app, container );
// This call should possibly be moved into the constructor for the AutofacAppBuilder ...
app.UseAutofacMiddleware(container);
// Rest of the middleware registration goes here ...
}
private static IContainer InitialiseContainer()
{
var builder = new ContainerBuilder();
// Register components into container
var container = builder.Build();
// Do any post build stuff as required
return container;
}
}
@randomcodenz
Copy link
Author

Purely theoretical. Allows the use of Autofac without breaking the conventions around OWIN and registering middleware. Could possibly be generalised to support any container.

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