Kar*_*ten 3 c# dependency-injection unity-container
我不知道如何以一种好的方式描述这一点,但是这里有.
我有4个班:A,B,C,D.
A注入B,C,D
C注入D.
A是每个决心.
B是单身人士.
C和DI不知道.
我希望A和C使用相同的D实例,所以每次从容器中解析A时,D应该创建一次并注入A和C.
最简单的方法是使A简单地将D传递给C而不使用Unity.但有没有办法用Unity做到这一点?我一直只使用ContainerControlledLifetimeManager和PerResolveLifetimeManager而且从不使用子容器,我怀疑这可能是有用的.我正在玩这个,但事实证明它非常混乱.可以轻松完成吗?
Joh*_*soe 11
您有更大的经营环境吗?在ASP.NET中,我创建了一个PerRequestLifetimeManager,它在单个HTTP请求期间多次请求时返回相同的对象.
编辑:如果你有兴趣,这是一个实现.
public class PerRequestLifetimeManager : LifetimeManager
{
private readonly object key = new object();
public override object GetValue()
{
if (HttpContext.Current != null && HttpContext.Current.Items.Contains(key))
return HttpContext.Current.Items[key];
else
return null;
}
public override void RemoveValue()
{
if (HttpContext.Current != null)
HttpContext.Current.Items.Remove(key);
}
public override void SetValue(object newValue)
{
if (HttpContext.Current != null)
HttpContext.Current.Items[key] = newValue;
}
Run Code Online (Sandbox Code Playgroud)