I have an interface IBase with many derived interfaces IDerived1, IDerived2. I would like to register implementations for the derived interfaces using Autofac.
Given any derived interface, I can write a resolve method for that interface. What I'm wondering is, is there any way that I can avoid enumerating a list of all derived interfaces when building the container?
What I have now is:
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 })
);
What I'd like to have is:
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 })
);
This would avoid me needing to know the full list of IDerived interfaces when the applications starts. Is this possible?
我能够使用自定义注册源解决此问题,该源可以为每个IDerived
接口服务类型IDerived
建立注册。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.