我有一个接口 IBase,其中包含许多派生接口 IDerived1、IDerived2。我想使用 Autofac 为派生接口注册实现。
给定任何派生接口,我可以为该接口编写解析方法。我想知道的是,有什么方法可以避免在构建容器时枚举所有派生接口的列表?
我现在拥有的是:
public static void Register<TDerived>(ContainerBuilder b) where TDerived : IBase {
b.Register(cc => DerivedFactory.Create<TDerived>(cc.Resolve<SomeDependency>())
.As<TDerived>()
.InstancePerLifetimeScope();
}
// in my registration method
ContainerBuilder b = ...
MethodInfo genericRegisterDerivedMethod = this.GetType().GetMethod("Register", BindingFlags.Public | BindingFlags.Static);
List<Type> allDerivedInterfaces = /* query across various assemblies for interfaces which extend IBase */
allDerivedInterfaces.ForEach(t => genericRegisterDerivedMethod
.MakeGenericMethod(t)
.Invoke(null, new object[] { b })
);
我想要的是:
public static void Create<TDerived>(IComponentContext cc) where TDerived : IBase {
return DerivedFactory.Create<TDerived>(cc.Resolve<SomeDependency>());
}
// in my registration method
ContainerBuilder b = ...
MethodInfo genericResolveDerivedMethod = this.GetType().GetMethod("Create", BindingFlags.Public | BindingFlags.Static);
b.RegisterDerivedTypesOf<IBase>((cc, t) => (IBase)genericResolveDerivedMethod
.MakeGenericMethod(t)
.Invoke(null, new object[] { cc, t })
);
这将避免我在应用程序启动时需要知道 IDerived 接口的完整列表。这可能吗?