Autofac delegate factories, and passing around container

拜拜、爱过 提交于 2019-12-24 12:01:07

问题


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:


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


来源:https://stackoverflow.com/questions/28165329/autofac-delegate-factories-and-passing-around-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!