public static IAppBuilder UseAutofacMiddleware(this IAppBuilder app, ILifetimeScope container) { if (app == null) { throw new ArgumentNullException("app"); } if (container == null) { throw new ArgumentNullException("container"); } return app .RegisterAutofacLifetimeScopeInjector(container) .UseAllMiddlewareRegisteredInContainer(container); }
private static IAppBuilder RegisterAutofacLifetimeScopeInjector(this IAppBuilder app, ILifetimeScope container) { app.Use(async (context, next) => { using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag, b => b.RegisterInstance(context).As())) { context.Set(Constants.OwinLifetimeScopeKey, lifetimeScope); await next(); } }); app.Properties[InjectorRegisteredKey] = true; return app; }
using System;using Microsoft.Owin;namespace Autofac.Integration.Owin{ ////// Extension methods for using Autofac within an OWIN context. /// public static class OwinContextExtensions { ////// Gets the current Autofac lifetime scope from the OWIN context. /// /// The OWIN context. ///The current lifetime scope. ////// Thrown if public static ILifetimeScope GetAutofacLifetimeScope(this IOwinContext context) { if (context == null) { throw new ArgumentNullException("context"); } return context.Getis . /// (Constants.OwinLifetimeScopeKey); } }}