我使用Castle Windsor注册了许多接口,每个接口都可以使用通用工厂方法创建。即。
container.Register(Component.For(typeof(IFirstService))
.UsingFactoryMethod(k => GetService<IFirstService>())
.LifeStyle.Singleton);
container.Register(Component.For(typeof(ISecondService))
.UsingFactoryMethod(k => GetService<ISecondService>())
.LifeStyle.Singleton);
我可以使用Types
方法一次性注册所有接口(所有接口都来自IService
),而不是为每个接口添加注册码,例如:
container.Register(Types
.FromThisAssembly()
.Where(t => typeof(IService).IsAssignableFrom(t))
.Configure(c => c.UsingFactoryMethod(k => GetService<?>()));
答案 0 :(得分:0)
因为泛型方法调用通常由编译器设置,所以在运行时不能完全不使用反射调用,但是使用object GetService(Type t)
签名而不是泛型参数可以执行此操作:
container.Register(Types.FromThisAssembly()
.BasedOn<IService>()
.Configure(c =>
c.UsingFactoryMethod((k, ctx) => GetService(ctx.RequestedType))
)
);
这是使用提供UsingFactoryMethod
的{{1}}重载。