【问题标题】:ASP Net Core StructureMap HybridLifecycle replacementASP Net Core StructureMap HybridLifecycle 替换
【发布时间】:2016-09-07 12:53:41
【问题描述】:
我目前正在更新为 ASP.NET MVC 5 构建的库,以便与使用 StructureMap 进行 DI 的最新 asp net core 1.0 一起使用。但是,我注意到 StructureMap 中的 Hybrid 生命周期现在是遗留的,不再受支持。有没有替代这个生命周期的方法,或者有办法获得相同的功能?
For<SessionContext>()
.LifecycleIs<HybridLifecycle>()
.Use<SessionContext>();
【问题讨论】:
标签:
c#
asp.net
asp.net-core
structuremap
【解决方案1】:
我最终编写了自己的 ASP 网络生命周期类,以将旧混合生命周期的相同功能与新的 ASP .Net 核心相匹配。
public class AspNetCoreLifecycle : ILifecycle {
private readonly object mapLock = new object();
public string Description => "Asp Net Core Lifecycle object";
private readonly Container container;
private Dictionary<HttpContext, IObjectCache> contextMap = new Dictionary<HttpContext, IObjectCache>();
public AspNetCoreLifecycle(Container cont) {
this.container = cont;
}
public void EjectAll(ILifecycleContext context) {
lock (mapLock) {
foreach (var kvp in contextMap) {
kvp.Value.DisposeAndClear();
}
contextMap = new Dictionary<HttpContext, IObjectCache>();
}
}
public IObjectCache FindCache(ILifecycleContext context) {
var accessor = container.GetInstance<IHttpContextAccessor>();
lock (mapLock) {
if (!contextMap.ContainsKey(accessor.HttpContext)) {
contextMap.Add(accessor.HttpContext, new LifecycleObjectCache());
}
return contextMap[accessor.HttpContext];
}
}
}