我在尝试使用Unity容器时实现自己的拦截.我希望以尊重所使用的终身经理的方式这样做.即如果它是一个PerResolveLifetimeManager,那么我想包装实例一次,我希望在整个解析过程中使用该包装实例.
到目前为止,我实现了一个BuilderStrategy,我使用自定义UnityContainerExtension类添加到我的容器中(我将PostInitialization传递给AddNew方法;我不确定最合适的值是什么,但这似乎有效).在我的BuilderStrategy中的PostBuildUp覆盖中,我将context.Existing替换为我的包装值.
当我在PerResolve生命周期中使用它时,会发生一次换行,但只有第一次使用依赖项才能获得包装的实例,其余的则获得一个非包装的实例.即如果我的ctor接收IFoo foo1和IFoo foo2那么只有foo1是我的包装实例,而foo2是未包装的实例.
这是一个示例repro(为简单起见,我使用另一个类的实例,Foo2,而不是包装):
public class MyInterception : UnityContainerExtension
{
protected override void Initialize()
{
Context.Strategies.AddNew<MyInterceptionStrategy>(UnityBuildStage.PostInitialization);
}
}
public class MyInterceptionStrategy : BuilderStrategy
{
public override void PostBuildUp(IBuilderContext context)
{
if (!context.OriginalBuildKey.Type.IsInterface)
{
return;
}
context.Existing = new Foo2();
}
}
public class Bar
{
public Bar(IFoo f1, IFoo f2, IFoo f3)
{
}
}
public interface IFoo
{
}
public class Foo1 : IFoo
{
}
public class Foo2 : IFoo
{
}
public void Main()
{ …Run Code Online (Sandbox Code Playgroud)