[英]Rebind generic interface in Ninject
我有幾個項目引用了包含通用接口的程序包
public interface IHandler<T> where T : class
{
void Handle(T data);
}
這些項目包含IHandler<>
實現和Ninject模塊,以及從接口到實現的綁定。
我想為所有IHandler<>
實現創建裝飾器
public class HandlerDecorator<T> : IHandler<T> where T : class
{
private readonly IHandler<T> decorated;
public HandlerDecorator(IHandler<T> decorated)
{
this.decorated = decorated;
}
public void Handle(T data)
{
// some logic
}
}
並自動IHandler<>
所有已注冊綁定。 例如,如果存在IHandler<string>
和StringHandler
綁定, IHandler<string>
將目標更改為new HandlerDecorator<string>(stringHandlerInstance)
。
Ninject有可能嗎? 還是應該重寫所有Ninject模塊代碼?
創建綁定后,由於無法訪問任何有意義的綁定信息,因此沒有直接的方法來完成此操作。 但是,您可以使用Ninject.Extensions.Conventions搜索所有IHandler<T>
實現,並將它們與裝飾器綁定/重新綁定。 在Ninject中,使用裝飾器需要為裝飾器綁定一個綁定,並為裝飾的實現綁定一個綁定。 如果您始終使用相同的裝飾器,則可以通過對裝飾器使用通用綁定來簡化它。 這將是:
kernel.Bind(typeof(IHandler<>)).To(typeof(HandlerDecorator));
(或使用Rebind
,而不是Bind
-如需要)。
使用約定擴展名創建的綁定應等於:
kernel.Bind<IHandler<string>>()
.To<StringHandler>()
.WhenInjectedInto<HandlerDecorator<string>>();
這可以通過以下方式實現:
kernel.Bind( x => x
.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(IHandler))
.Excluding(typeof(HandlerDecorator<>))
.BindDefaultInterface()
.Configure(b => b.WhenInjectedInto(typeof(HandlerDecorator<>)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.