我有一个带有许多派生接口IDerived1,IDerived2的接口IBase。我想使用Autofac注册派生接口的实现。
给定任何派生接口,我可以为该接口编写一个resolve方法。我想知道的是,有什么办法可以避免在构建容器时枚举所有派生接口的列表吗?
我现在拥有的是:
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接口的完整列表。这可能吗?
答案 0 :(得分:0)
我能够使用自定义注册源解决此问题,该注册源可以为所请求的每个IDerived
接口服务类型动态构建注册。