如何延长Ninject绑定语法(How to extend Ninject Binding Synt

2019-10-16 15:00发布

有没有办法来扩展现有的绑定语法(如扩展方法),这将让我们有这样的事情:

Bind<IRepository>().ToProvider<MyProvider<MyRepository>>().WhenCustom<SomeType>()

Answer 1:

写为一个扩展方法IBindingWhenSyntax<T>和使用现有的When过载来实现你的逻辑:

class BindingWhenExtensions
{
   public IBindingInNamedWithOrOnSyntax<T> WhenCustom<T>(
       this IBindingWhenSyntax<T> syntax)
   { 
        return syntax.When(r => true); 
   }
}


Answer 2:

重新定义的问题(与您的意见一致),你想创建一个类似于以下签名的延伸;

public static IBindingInNamedWithOrOnSyntax<T> WhenCustom<TParent>(
            this IBindingWhenSyntax<T> binding)

据我可以告诉我们不能因为这与Ninject干净利落延长,因为当你正确地影射T这里定义的接口上 ,我们的扩展不知道。

所以,我们的扩展签名必须是;

public static IBindingInNamedWithOrOnSyntax<T> WhenCustom<T>(
            this IBindingWhenSyntax<T> binding)

在这一点上,我看到我们能够成功地传递的唯一途径TParent是放弃泛型参数,并把它作为一个标准的类型参数(或通过几种类型);

 public static IBindingInNamedWithOrOnSyntax<T> WhenCustom(
            this IBindingWhenSyntax<T> binding, params Type[] parents)

这仍与Ninjects一致自己绑定语法的方法;

/// <summary>
/// Indicates that the binding should be used only for injections on the specified types.
/// Types that derive from one of the specified types are considered as valid targets.
/// Should match at lease one of the targets.
/// </summary>
/// <param name="parents">The types to match.</param>
/// <returns>The fluent syntax.</returns>
IBindingInNamedWithOrOnSyntax<T> WhenInjectedInto(params Type[] parents);

这只是不幸的是,我们没有与“纯”仿制药延长的奢侈品。



文章来源: How to extend Ninject Binding Syntax
标签: ninject