繁体   English   中英

在温莎城堡动态注册类型

[英]Dynamically register types in Castle Windsor

假设我有一个接口和类:(出于询问目的,它将为空)

public interface IPerson { }

public class Tom : IPerson {}
public class Philip : IPerson {}

以及服务接口及其实现:

public interface IHelloService<T> where T : IPerson { }

public class HelloService<T> : IHelloService<T> where T : IPerson { }

如何为每个IProdukt动态注册服务HelloService ,我的意思是我想注册此类:

IHelloService<Tom> -> HelloService<Tom>
IHelloService<Philip> -> HelloService<Philip>

也许您追求的是这样的事情:

container.Register(Component.For(typeof(IHelloService<>))
    .ImplementedBy(typeof(HelloService<>), new Only<IProduct>())
    .LifestyleTransient());

public class Only<T> : IGenericServiceStrategy
{
    public bool Supports(Type service, ComponentModel component) => typeof(T).IsAssignableFrom(service.GetGenericArguments()[0]);
}

它将使用与服务相同的类型参数关闭实现,但是它将可能的类型参数限制为实现IProdukt / IPerson的类型(我想这些含义是相同的吗?)。

请在此处查看此功能的说明: http : //kozmic.net/2013/07/23/on-castle-windsor-and-open-generic-components/

暂无
暂无

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

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