Using Autofac to provide types exported by static factory

非 Y 不嫁゛ 提交于 2020-01-07 05:08:10

问题


I have a dependency which provides a number of services using its static ServiceManager. It also provides a list of available types.

Type[] ServiceManager.GetServiceTypes();
object GetService(Type t);

In an Autofac Module, I'd like to enumerate these types and register 'dynamic instantiation' of them. It's important that I call ServiceManager.GetService each time an instance is requested.


回答1:


I ended up using my own RegistrationBuilder, looks pretty funky but it works. Have I missed an obvious trick?

        foreach (var type in ServiceManager.GetServiceTypes())
        {
            var rb = RegistrationBuilder.ForDelegate(
                type, 
                (ctx, parms) => ServiceManager.GetService(type))
                .ExternallyOwned();

            builder.RegisterCallback(
                cr => RegistrationBuilder.RegisterSingleComponent(cr, rb));
        }


来源:https://stackoverflow.com/questions/7777247/using-autofac-to-provide-types-exported-by-static-factory

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