Autofac的委托工厂,以及容器的传递 [英] Autofac delegate factories, and passing around container
问题描述
我对委托工厂有疑问: autofac文档
I have a question about delegate factories: autofac docs
我了解他们是如何建立工厂的,但是我没有解决问题的部分:
I understand how they set up the factories but I do not get the resolving part:
var shareholdingFactory = container.Resolve<Shareholding.Factory>();
var shareholding = shareholdingFactory.Invoke("ABC", 1234);
看来您必须绕过容器才能解决.也许我必须使用仅在运行时才知道的参数来调用某些东西.如何在不将容器传递给例如服务方法的情况下做到这一点?
It looks like you have to pass around the container in order to resolve. Maybe I have to Invoke something with parameters I only know at runtime. How do I do that without passing the container to for example a service method?
更新
那么您应该通过工厂?
So you are supposed to pass the factories instead?
推荐答案
Autofac可以自动解析工厂,即没有容器:
Autofac can automatically resolve factories, i.e. without the container:
public class ShareHolding
{
public ShareHolding(int accountId)
{
// do whatever you want
}
}
public class MyApp
{
private readonly ShareHolding _shareHolding;
public MyApp(Func<int, ShareHolding> shareHoldingFactory)
{
_shareHolding = shareHoldingFactory(99);
}
public void Run()
{
// do whatever you want with the _shareHolding object
}
}
Autofac注册
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<ShareHolding>(); // not a singleton
containerBuilder.RegisterType<MyApp>().SingeInstance();
var myApp = containerBuilder.Resolve<MyApp>();
myApp.Run();
现在,如果您的ShareHolding类型的ctor像这样:
Now, if your ShareHolding type had ctor like:
public class ShareHolding
{
public delegate ShareHolding Factory(int accountId, int userId);
public ShareHolding(int accountId, int userId)
{
// do whatever you want
}
}
然后,您将需要一个委托工厂,因为Autofac使用类型信息来解析构造函数,而使用参数名称来委托工厂.您的用法将变为:
Then you would need a delegate factory because Autofac resolves constructors using type information and delegate factories using parameters names. Your usage would then become:
public class MyApp
{
public MyApp(ShareHolding.Factory shareHoldingFactory)
{
....
}
}
这篇关于Autofac的委托工厂,以及容器的传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!