我想为Unity版本3.5实现一个处置瞬态生命周期管理器。问题是我不知道如何访问LifetimeManager
等中的PostTearDown
。 BuilderStrategy
类的步骤。 context.Lifetime
在Unity 2中运行良好。
基本上我有以下内容:
Container = new UnityContainer();
Container.AddNewExtension<DisposableStrategyExtension>();
Container.RegisterType<ITest, Test>(new DisposingTransientLifetimeManager());
public class DisposingLifetimeStrategy : BuilderStrategy
{
public override void PreBuildUp(IBuilderContext context)
{
base.PreBuildUp(context);
// context.Lifetime.Count == 0 here and in all other methods.
// In version 2 of unity this is set.
}
// implement rest of methods, but context.Lifetime.Count is 0 in all of them too.
public class DisposingTransientLifetimeManager : LifetimeManager
// implement abstract methods minimally
答案 0 :(得分:1)
您可以从政策列表中获取终身经理:
public class DisposingLifetimeStrategy : BuilderStrategy
{
public override void PreBuildUp(IBuilderContext context)
{
ILifetimePolicy lifeTime = context.Policies.Get<ILifetimePolicy>(context.BuildKey);
base.PreBuildUp(context);
}
public override void PreTearDown(IBuilderContext context)
{
// Assumes registration name is null
var buildKey = new NamedTypeBuildKey(context.Existing.GetType());
ILifetimePolicy lifeTime = context.Policies.Get<ILifetimePolicy>(buildKey);
base.PreTearDown(context);
}
}
如果您正在调用IUnityContainer.Teardown(obj),则PreTearDown和PostTearDown方法将不知道已解析对象的名称。只要存在默认(null)注册(因为我假设您只想将对象转换为IDisposable
然后Dispose对象),这可能无关紧要。