我不知道如何用一种好的方式来描述它,但就是这样。
我有 4 个类(class):A、B、C、D。
A注入(inject)了B,C,D
C注入(inject)D
A 是每次解析。
B是单例。
C 和 D 我不知道。
我希望 A 和 C 使用相同的 D 实例,所以每次我从容器中解析 A 时,都应该创建一次 D 并将其注入(inject)到 A 和 C 中。
最简单的方法是让 A 在不使用 Unity 的情况下简单地将 D 传递给 C。但是有没有办法用 Unity 做到这一点?我一直只使用 ContainerControlledLifetimeManager 和 PerResolveLifetimeManager 而从不使用我怀疑可能有用的子容器。我一直在玩这个,但结果很乱。可以轻松完成吗?
最佳答案
您的经营范围是否更大?在 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;
}
关于c# - 统一和生命周期管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4747653/