针对相同的匹配生存期范围注册多个组件
本文关键字:注册 范围 组件 生存期 | 更新日期: 2023-09-27 18:22:13
我有一堆组件需要按照匹配的生存期范围(InstancePerMatchingLifetimeScope)进行解析。
然而,我必须逐一为它们中的每一个指定它。
例如)
builder.RegisterType<LukeSkywalker>().As<IJedi>().InstancePerMatchingLifetimeScope("starwars");
builder.RegisterType<ObiwanKenobi>().As<IJedi>().InstancePerMatchingLifetimeScope("starwars");
builder.RegisterType<MasterYoda>().As<IJedi>().InstancePerMatchingLifetimeScope("starwars");
...
然后你就明白了。有没有办法指定"所有这些"都是InstancePerMatchingLifetimeScope?
类似(伪代码):
[
builder.RegisterType<LukeSkywalker>().As<IJedi>(),
builder.RegisterType<ObiwanKenobi>().As<IJedi>(),
builder.RegisterType<MasterYoda>().As<IJedi>(),
].InstancePerMatchingLifetimeScope("starwars");
builder.RegisterType<LukeSkywalker>().As<IJedi>()
返回一个类型为IRegistrationBuilder<out TLimit, out TActivatorData, out TRegistrationStyle>
的对象,因此您可以为该类型创建自己的方法。
public static class RegistrationsExtensions
{
public static IRegistrationBuilder<TLimit, TActivatorData, TStyle> InstancePerStarwars<TLimit, TActivatorData, TStyle>(this IRegistrationBuilder<TLimit, TActivatorData, TStyle> registration)
{
return registration.InstancePerMatchingLifetimeScope("starwars");
}
}
这样称呼它:
builder.RegisterType<LukeSkywalker>().As<IJedi>().InstancePerStarwars()
您还可以创建另一种方法来扩展ContainerBuilder
:
public static void InstancePerStarwars<TLimit, TActivatorData, TStyle>(this ContainerBuilder builder, params IRegistrationBuilder<TLimit, TActivatorData, TStyle>[] registrations)
{
foreach (IRegistrationBuilder<TLimit, TActivatorData, TStyle> registration in registrations)
{
registration.InstancePerStarwars();
}
}
然后,你将能够做到这一点:
builder.InstancePerStarwars(
new IRegistrationBuilder<Object, ReflectionActivatorData, SingleRegistrationStyle>[] {
builder.RegisterType<LukeSkywalker>().As<IJedi>(),
builder.RegisterType<ObiwanKenobi>().As<IJedi>(),
builder.RegisterType<MasterYoda>().As<IJedi>()
});