繁体   English   中英

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))
    )
);

这使用提供CreationContextUsingFactoryMethod重载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM