Autofac 委托工厂,并传递容器

And*_*eas 1 c# dependency-injection autofac

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

我了解他们如何建立工厂,但我没有得到解决部分:

var shareholdingFactory = container.Resolve<Shareholding.Factory>();
var shareholding = shareholdingFactory.Invoke("ABC", 1234);
Run Code Online (Sandbox Code Playgroud)

看起来您必须绕过容器才能解决。也许我必须使用我只在运行时知道的参数来调用一些东西。如何在不将容器传递给例如服务方法的情况下做到这一点?

更新

所以你应该通过工厂?

Rus*_*kin 5

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
    }
}
Run Code Online (Sandbox Code Playgroud)

自动注册

var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<ShareHolding>(); // not a singleton
containerBuilder.RegisterType<MyApp>().SingeInstance();

var myApp = containerBuilder.Resolve<MyApp>();
myApp.Run();
Run Code Online (Sandbox Code Playgroud)

现在,如果你的 ShareHolding 类型有 ctor 像:

public class ShareHolding
{
    public delegate ShareHolding Factory(int accountId, int userId);
    public ShareHolding(int accountId, int userId)
    {
        // do whatever you want
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public class MyApp
{
    public MyApp(ShareHolding.Factory shareHoldingFactory)
    {
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)