开发者

Using Autofac to provide types exported by static factory

开发者 https://www.devze.com 2023-04-13 00:11 出处:网络
I have a dependency which provides a number of services using its static ServiceManager.It also provides a list of available types.

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 Mod开发者_运维知识库ule, 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.


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));
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号