根据Castle Windsor文档,您可以实现自己的自定义范围,需要实现
Castle.MicroKernel.Lifestyle.Scoped.IScopeAccessor
接口。然后在注册组件时指定您的范围访问器。
Container.Register(Component.For<MyScopedComponent>().LifestyleScoped<OwinWebRequestScopeAccessor >())
类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();
}
}
}
正如您所看到的,OwinWebRequestScopeAccessor
将调用委托给PerWebRequestLifestyleOwinMiddleware
的GetScope和Dispose方法。
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);
}
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
{
public static IAppBuilder UsePerWebRequestLifestyleOwinMiddleware(this IAppBuilder app)
{
return app.Use(typeof(PerWebRequestLifestyleOwinMiddleware));
}
}
}
Castle Windsor的ASP.NET IHttpModule PerWebRequestLifestyleModule
使用HttpContext.Current
在每个web请求上存储Castle Windsor ILifetimeScope
。而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>();
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();
}
}
}
}
在所有准备工作就绪后,您可以开始整理好各项内容。在您的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();
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
appBuilder.UseWebApi(config);
}
public void Close()
{
if (_container != null)
_container.Dispose();
}
}
}
样例的WindsorInstaller类展示了如何使用OWIN每个Web请求范围:
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);
}
}
}
我所提出的解决方案基于现有的
/src/Castle.Windsor/MicroKernel/Lifestyle/PerWebRequestLifestyleModule.cs
和Yoshifumi Kawai原始的
OwinRequestScopeContext
。
OwinRequestScopeContext
存储在System.Runtime.Remoting.Messaging.CallContext
中。我的第一个想法是将其存储在Owin环境字典 (OwinContext.Environment
)中。 - Andrew ShepherdSystem.Runtime.Remoting.Messaging.CallContext
具有全局可访问的静态成员,但是没有安全的方式来静态获取OwinContext
。 - Andrew Shepherd