Autofac 委托工厂,并传递容器

Autofac delegate factories, and passing around container

我有一个关于委托工厂的问题:autofac docs

我了解他们是如何建立工厂的,但我不明白解决问题的部分:

var shareholdingFactory = container.Resolve<Shareholding.Factory>();
var shareholding = shareholdingFactory.Invoke("ABC", 1234);

看来你必须绕过容器才能解析。也许我必须使用我只在运行时知道的参数调用一些东西。如果不将容器传递给服务方法,我该怎么做?

更新

所以你应该通过工厂?

Autofac 可以自动解析工厂,即没有容器:

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 类型有这样的构造函数:

public class ShareHolding
{
    public delegate ShareHolding Factory(int accountId, int userId);
    public ShareHolding(int accountId, int userId)
    {
        // do whatever you want
    }
}

那么您将需要一个委托工厂,因为 Autofac 使用类型信息解析构造函数,并使用参数名称解​​析委托工厂。您的用法将变为:

public class MyApp
{
    public MyApp(ShareHolding.Factory shareHoldingFactory)
    {
        ....
    }
}