Autofac委托工厂,并绕过集装箱

时间:2015-01-27 07:29:26

标签: c# dependency-injection autofac

我对代表工厂有疑问:autofac docs

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

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

看起来你必须绕过容器才能解决。也许我必须使用我在运行时才知道的参数来调用。如何在不将容器传递给服务方法的情况下执行此操作?

更新

所以你应该通过工厂呢?

1 个答案:

答案 0 :(得分:4)

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类型有ctor:

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)
    {
        ....
    }
}