使用Autofac提供静态工厂导出的类型

使用Autofac提供静态工厂导出的类型

本文介绍了使用Autofac提供静态工厂导出的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个依赖项,使用它的静态ServiceManager可以提供许多服务.它还提供了可用类型的列表.

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

在Autofac模块中,我想枚举这些类型并注册它们的动态实例化".每次请求实例时,都要调用ServiceManager.GetService.

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.

推荐答案

我最终使用了自己的RegistrationBuilder,看上去很时髦,但是可以用.我错过了一个明显的把戏吗?

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

这篇关于使用Autofac提供静态工厂导出的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:38