如何在OWIN中使用Castle Windsor的PerWebRequest生活方式

Tal*_*lon 6 c# castle-windsor perwebrequest asp.net-web-api owin

我正在转换现有的ASP .Net Web API 2项目以使用OWIN.该项目使用Castle Windsor作为依赖注入框架,其中一个依赖项设置为使用PerWebRequest生活方式.

当我向服务器发出请求时,我得到一个Castle.MicroKernel.ComponentResolutionException例外.该异常建议将以下内容添加到配置文件中的system.web/httpModulessystem.WebServer/modules部分:

<add name="PerRequestLifestyle"
     type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
Run Code Online (Sandbox Code Playgroud)

这不能解决错误.

从SimpleInjector的OWIN集成提供的示例中获取灵感,我尝试使用以下方法在OWIN启动类中设置范围(以及更新依赖关系的生活方式):

appBuilder.User(async (context, next) =>
{
    using (config.DependencyResolver.BeginScope()){
    {
        await next();
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这也没有用.

我如何使用Castle Windsor的PerWebRequest生活方式或在OWIN中模拟它?

Joh*_*tra 8

根据Castle Windsor文档,您可以实现自己的自定义范围.您必须实现该Castle.MicroKernel.Lifestyle.Scoped.IScopeAccessor接口.

然后在注册组件时指定范围访问器:

Container.Register(Component.For<MyScopedComponent>().LifestyleScoped<OwinWebRequestScopeAccessor >());
Run Code Online (Sandbox Code Playgroud)

该类OwinWebRequestScopeAccessor实现了Castle.Windsor IScopeAccessor:

using Castle.MicroKernel.Context;
using Castle.MicroKernel.Lifestyle.Scoped;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Web.Api.Host
{
    public class OwinWebRequestScopeAccessor : IScopeAccessor
    {
        public void Dispose()
        {
            var scope = PerWebRequestLifestyleOwinMiddleware.YieldScope();
            if (scope != null)
            {
                scope.Dispose();
            }
        }

        public ILifetimeScope GetScope(CreationContext context)
        {
            return PerWebRequestLifestyleOwinMiddleware.GetScope();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所见,OwinWebRequestScopeAccessor委托调用GetScopeDispose to PerWebRequestLifestyleOwinMiddleware.

该类PerWebRequestLifestyleOwinMiddleware是Castle Windsor的ASP.NET IHttpModule PerWebRequestLifestyleModule的OWIN计数器部分.

这是PerWebRequestLifestyleOwinMiddleware班级:

using Castle.MicroKernel;
using Castle.MicroKernel.Lifestyle.Scoped;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Web.Api.Host
{
    using AppFunc = Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;

    public class PerWebRequestLifestyleOwinMiddleware
    {
        private readonly AppFunc _next;
        private const string c_key = "castle.per-web-request-lifestyle-cache";
        private static bool _initialized;

        public PerWebRequestLifestyleOwinMiddleware(AppFunc next)
        {
            _next = next;
        }

        public async Task Invoke(IDictionary<string, object> environment)
        {
            var requestContext = OwinRequestScopeContext.Current;
            _initialized = true;

            try
            {
                await _next(environment);
            }
            finally
            {
                var scope = GetScope(requestContext, createIfNotPresent: false);
                if (scope != null)
                {
                    scope.Dispose();
                }
                requestContext.EndRequest();
            }
        }

        internal static ILifetimeScope GetScope()
        {
            EnsureInitialized();
            var context = OwinRequestScopeContext.Current;
            if (context == null)
            {
                throw new InvalidOperationException(typeof(OwinRequestScopeContext).FullName +".Current is null. " +
                    typeof(PerWebRequestLifestyleOwinMiddleware).FullName +" can only be used with OWIN.");
            }
            return GetScope(context, createIfNotPresent: true);
        }

        /// <summary>
        /// Returns current request's scope and detaches it from the request 
        /// context. Does not throw if scope or context not present. To be 
        /// used for disposing of the context.
        /// </summary>
        /// <returns></returns>
        internal static ILifetimeScope YieldScope()
        {
            var context = OwinRequestScopeContext.Current;
            if (context == null)
            {
                return null;
            }
            var scope = GetScope(context, createIfNotPresent: false);
            if (scope != null)
            {
                context.Items.Remove(c_key);
            }
            return scope;
        }

        private static void EnsureInitialized()
        {
            if (_initialized)
            {
                return;
            }
            throw new ComponentResolutionException("Looks like you forgot to register the OWIN middleware " + typeof(PerWebRequestLifestyleOwinMiddleware).FullName);
        }

        private static ILifetimeScope GetScope(IOwinRequestScopeContext context, bool createIfNotPresent)
        {
            ILifetimeScope candidates = null;
            if (context.Items.ContainsKey(c_key))
            {
                candidates = (ILifetimeScope)context.Items[c_key];
            }
            else if (createIfNotPresent)
            {
                candidates = new DefaultLifetimeScope(new ScopeCache());
                context.Items[c_key] = candidates;
            }
            return candidates;
        }
    }

    public static class AppBuilderPerWebRequestLifestyleOwinMiddlewareExtensions
    {
        /// <summary>
        /// Use <see cref="PerWebRequestLifestyleOwinMiddleware"/>.
        /// </summary>
        /// <param name="app">Owin app.</param>
        /// <returns></returns>
        public static IAppBuilder UsePerWebRequestLifestyleOwinMiddleware(this IAppBuilder app)
        {
            return app.Use(typeof(PerWebRequestLifestyleOwinMiddleware));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

温莎城堡的ASP.NET的IHttpModule PerWebRequestLifestyleModule利用HttpContext.Current存储在温莎城堡ILifetimeScope上的每个Web请求的基础.PerWebRequestLifestyleOwinMiddleware课堂使用OwinRequestScopeContext.Current.这是基于Yoshifumi Kawai的想法.

下面的实现OwinRequestScopeContext是我对Yoshifumi Kawai原创的轻量级实现OwinRequestScopeContext.


注意:如果您不想要这个轻量级实现,可以通过在NuGet包管理器控制台中运行此命令来使用Yoshifumi Kawai的优秀原始实现:

PM> Install-Package OwinRequestScopeContext


轻量级实现OwinRequestScopeContext:

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Web.Api.Host
{
    public interface IOwinRequestScopeContext
    {
        IDictionary<string, object> Items { get; }
        DateTime Timestamp { get; }
        void EndRequest();
    }

    public class OwinRequestScopeContext : IOwinRequestScopeContext
    {
        const string c_callContextKey = "owin.reqscopecontext";
        private readonly DateTime _utcTimestamp = DateTime.UtcNow;
        private ConcurrentDictionary<string, object> _items = new ConcurrentDictionary<string, object>();

        /// <summary>
        /// Gets or sets the <see cref="IOwinRequestScopeContext"/> object 
        /// for the current HTTP request.
        /// </summary>
        public static IOwinRequestScopeContext Current
        {
            get
            {
                var requestContext = CallContext.LogicalGetData(c_callContextKey) as IOwinRequestScopeContext;
                if (requestContext == null)
                {
                    requestContext = new OwinRequestScopeContext();
                    CallContext.LogicalSetData(c_callContextKey, requestContext);
                }
                return requestContext;
            }
            set
            {
                CallContext.LogicalSetData(c_callContextKey, value);
            }
        }

        public void EndRequest()
        {
            CallContext.FreeNamedDataSlot(c_callContextKey);
        }

        public IDictionary<string, object> Items
        {
            get
            {
                return _items;
            }
        }

        public DateTime Timestamp
        {
            get
            {
                return _utcTimestamp.ToLocalTime();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你有所有的部件,你可以绑定.在您的OWIN启动类中,调用appBuilder.UsePerWebRequestLifestyleOwinMiddleware();扩展方法来注册上面定义的OWIN中间件.之前这样做appBuilder.UseWebApi(config);:

using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Diagnostics;
using Castle.Windsor;
using System.Web.Http.Dispatcher;
using System.Web.Http.Tracing;

namespace Web.Api.Host
{
    class Startup
    {
        private readonly IWindsorContainer _container;

        public Startup()
        {
            _container = new WindsorContainer().Install(new WindsorInstaller());
        }

        public void Configuration(IAppBuilder appBuilder)
        {
            var properties = new Microsoft.Owin.BuilderProperties.AppProperties(appBuilder.Properties);
            var token = properties.OnAppDisposing;
            if (token != System.Threading.CancellationToken.None)
            {
                token.Register(Close);
            }

            appBuilder.UsePerWebRequestLifestyleOwinMiddleware();

            //
            // Configure Web API for self-host. 
            //
            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
            appBuilder.UseWebApi(config);
        }

        public void Close()
        {
            if (_container != null)
                _container.Dispose();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例WindsorInstaller类显示了如何使用OWIN per-web-request范围:

using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Web.Api.Host
{
    class WindsorInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(Component
                .For<IPerWebRequestDependency>()
                .ImplementedBy<PerWebRequestDependency>()
                .LifestyleScoped<OwinWebRequestScopeAccessor>());

            container.Register(Component
                .For<Controllers.V1.TestController>()
                .LifeStyle.Transient);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我上面提出的解决方案是基于现有的/src/Castle.Windsor/MicroKernel/Lifestyle/PerWebRequestLifestyleModule.cs和Yoshifumi Kawai的原始OwinRequestScopeContext.


And*_*erd 6

我尝试实现Johan Boonstra的答案,但发现一旦我们使用ASP.NET MVC Controller方法它就无法正常工作.

这是一个更简单的解决方案:

首先,创建一些位于管道起点的Owin中间件并创建一个 DefaultLifetimeScope

public class WebRequestLifestyleMiddleware : OwinMiddleware
{
    public const string EnvironmentKey = "WindsorOwinScope";

    public WebRequestLifestyleMiddleware(OwinMiddleware next) : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        ILifetimeScope lifetimeScope = new DefaultLifetimeScope();
        context.Environment[EnvironmentKey] = lifetimeScope;
        try
        {
            await this.Next.Invoke(context);
        }
        finally
        {
            context.Environment.Remove(EnvironmentKey);
            lifetimeScope.Dispose();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在启动配置中将其插入管道的开头:

public void Configure(IAppBuilder appBuilder)
{
    appBuilder.Use<WebRequestLifestyleMiddleware>();

    //
    // Further configuration
    //
}
Run Code Online (Sandbox Code Playgroud)

现在,您创建一个实现IScopeAccessor并获取WebRequestLifestyleMiddleware推入环境的范围的类:

public class OwinWebRequestScopeAccessor : IScopeAccessor
{
    void IDisposable.Dispose() { }

    ILifetimeScope IScopeAccessor.GetScope(CreationContext context)
    {
        IOwinContext owinContext = HttpContext.Current.GetOwinContext();
        string key = WebRequestLifestyleMiddleware.EnvironmentKey;
        return owinContext.Environment[key] as ILifetimeScope;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,在注册组件生命周期时使用此范围访问器.例如,我有AccessCodeProvider一个我想要在一个请求中重用的自定义组件:

container.Register(
      Component.For<AccessCodeProvider>()
               .LifestyleScoped<OwinRequestScopeAccessor>()
);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,AccessCodeProvider将在请求中第一次询问时创建,然后在整个Web请求中重用,最后在WebRequestLifestyleMiddleware调用时处理lifetimeScope.Dispose().

  • 我发现这非常有用,但在我的情况下,我使用自托管和HttpContext.Current对我不起作用...而是使用了'OwinRequestScopeContext` nuget包(https://github.com/neuecc/OwinRequestScopeContext /)然后我只需要修改该行以将OwinContext转换为`IOwinContext owinContext = new Microsoft.Owin.OwinContext(OwinRequestScopeContext.Current.Environment);`并且它有效. (3认同)
  • 对我来说效果很好,除了线程问题。应该将DefaultLifetimeScope替换为[ThreadSafeDefaultLifetimeScope](https://github.com/castleproject/Windsor/blob/master/docs/implementing-custom-scope.md#the-scope-abstraction-ilifetimescope)线程环境 (2认同)