gpt4 book ai didi

c# - 确定解决实例的依赖关系 - IoC (autofac)

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:54 25 4
gpt4 key购买 nike

有没有办法确定哪个调用者/依赖项正在解析它所依赖的实例?这就是我的想法

public class A
{
public A()
{
Console.Write("I am being resolved by {0}");
}
}

public class B
{
public B(A a)
{
//Should print: A being resolved by B
}
}


public class C
{
public C(A a)
{
//Should print: A being resolved by C
}
}

我猜测对于跨多个依赖项共享的单个实例可能有点棘手,但我专门寻找每个依赖项解析的实例,因此在上面的示例中将有两个 B 实例。

FWIW,我的 IoC 容器是 Autofac,它在 MVC 网络应用程序的上下文中运行

最佳答案

您可以使用 ResolveOperationBeggingInstanceLookupBeginning 事件

    ContainerBuilder builder = new Autofac.ContainerBuilder();
builder.RegisterType<A>().AsSelf();
builder.RegisterType<B>().AsSelf();
builder.RegisterType<C>().AsSelf();

IContainer container = builder.Build();

EventHandler<LifetimeScopeBeginningEventArgs> lifetimeScopeBeginning = null;
lifetimeScopeBeginning = (sender, e) =>
{
e.LifetimeScope.ResolveOperationBeginning += (sender2, e2) =>
{
List<IInstanceActivator> activators = new List<IInstanceActivator>();
e2.ResolveOperation.InstanceLookupBeginning += (sender3, e3) =>
{
activators.Add(e3.InstanceLookup.ComponentRegistration.Activator);
Console.WriteLine("Activation Path : {0}", String.Join(" => ", activators.Select(a => a.LimitType.Name).ToArray()));
};
};
e.LifetimeScope.ChildLifetimeScopeBeginning += lifetimeScopeBeginning;
};
container.ChildLifetimeScopeBeginning += lifetimeScopeBeginning;

using (ILifetimeScope scope = container.BeginLifetimeScope())
{
scope.Resolve<C>();
}

这段代码会显示

Activation Path : C
Activation Path : C => B
Activation Path : C => B => A

关于c# - 确定解决实例的依赖关系 - IoC (autofac),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28645099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com