我正在创建一个DI便利性Nuget软件包,该软件包将添加简单的组件(以.AddEntityFramework()
-类似方法(的方式添加一个函数注册,以与我的主包一起使用。p>基本上,库的用户将注册一个或多个IService
(Singleton(实例,然后调用我的方法RegisterServiceHelpers()
。
我要做的是为用户注册的每个IService
注册一个助手。示例方法(不工作(
public static void RegisterServiceHelpers(this ContainerBuilder self)
{
foreach (var service in self.Build().Resolve<IEnumerable<IService>>())
self.Register(c =>
new ServiceHelper(service)).SingleInstance();
}
这是不可能的,因为AUTOFAC仅允许一次调用.Build()
。
我也试图利用类似的隐式列表支持
self.Register(c => c.Resolve<IEnumerable<MessageBusFactory>>()
.Select(factory =>
new RabbitMqHealthCheckHandler(
factory,
c.Resolve<ILogger<RabbitMqHealthCheckHandler>>())))
.SingleInstance()
.As<IEnumerable<IHealthCheckHandler>>();
但这不起作用,更不用说SingleInstance()
上的错误范围
模块的AttachToComponentRegistration
方法让您添加动态注册。
class XModule : Module
{
protected override void AttachToComponentRegistration(
IComponentRegistry componentRegistry, IComponentRegistration registration)
{
base.AttachToComponentRegistration(componentRegistry, registration);
if (registration.Services.OfType<IServiceWithType>()
.Any(s => s.ServiceType == typeof(IService)))
{
IComponentRegistration r = RegistrationBuilder
.ForType<ServiceHelper>()
.WithParameter(
(pi, c) => pi.ParameterType == typeof(IService),
(pi, c) => c.ResolveComponent(
registration, Enumerable.Empty<Parameter>()))
.SingleInstance()
.CreateRegistration();
componentRegistry.Register(r);
}
}
}
然后您可以像builder.RegisterModule<XModule>()