簡體   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