Autofac delegate factories, and passing around con

2019-09-16 01:57发布

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?

UPDATE

So you are supposed to pass the factories instead?

1条回答
趁早两清
2楼-- · 2019-09-16 02:30

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 registration

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

var myApp = containerBuilder.Resolve<MyApp>();
myApp.Run();

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
    }
}

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)
    {
        ....
    }
}
查看更多
登录 后发表回答