Autofac.Integration.Mvc.Owin分析

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Web;
using Autofac;
using Autofac.Integration.Owin;

namespace Owin
{
    /// <summary>
    /// Extension methods for configuring the OWIN pipeline.
    /// </summary>
    [SecuritySafeCritical]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class AutofacMvcAppBuilderExtensions
    {
        internal static Func<HttpContextBase> CurrentHttpContext = () => new HttpContextWrapper(HttpContext.Current);

        /// <summary>
        /// Extends the Autofac lifetime scope added from the OWIN pipeline through to the MVC request lifetime scope.
        /// </summary>
        /// <param name="app">The application builder.</param>
        /// <returns>The application builder.</returns>
        [SecuritySafeCritical]
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        public static IAppBuilder UseAutofacMvc(this IAppBuilder app)
        {
            return app.Use(async (context, next) =>
            {
                var lifetimeScope = context.GetAutofacLifetimeScope();
                var httpContext = CurrentHttpContext();

                if (lifetimeScope != null && httpContext != null)
                    httpContext.Items[typeof(ILifetimeScope)] = lifetimeScope;

                await next();
            });
        }
    }
}

 

posted @ 2016-06-08 04:07  shiningrise  阅读(405)  评论(0编辑  收藏  举报