Castle Windsor - 使用相同的通用工厂方法注册多个接口

Castle Windsor - Registering multiple interfaces with same generic factory method

我正在使用 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<?>()));

因为泛型方法调用通常由编译器设置,如果不使用反射调用,你不能在运行时完全做到这一点,但是使用 object GetService(Type t) 签名而不是泛型参数,你可以这样做:

container.Register(Types.FromThisAssembly()
    .BasedOn<IService>()
    .Configure(c =>
        c.UsingFactoryMethod((k, ctx) => GetService(ctx.RequestedType))
    )
);

这是使用提供 CreationContext.

UsingFactoryMethod 重载