How to extend Ninject Binding Syntax

只愿长相守 提交于 2019-12-11 05:36:57

问题


is there a way to extend the existing binding syntax (e.g. extension method) that will allow us to have something like this:

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

回答1:


Write an extension method for IBindingWhenSyntax<T> and use the existing When overload to implement your logic:

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



回答2:


Reframing the question (to align with your comment) you want to create an extension with a signature similar to the following;

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

As far as I can tell we're not able to extend as cleanly as this with Ninject because as you rightly allude to T here is defined on an interface that our extension doesn't know about.

So our extension signature must be;

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

At this point the only way I see us being able to successfully pass TParent is to drop the generic parameter and pass it as a standard type parameter (or pass several types);

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

This is still consistent with Ninjects own binding syntax methods;

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

It's just unfortunate that we don't have the luxury of extending with 'pure' generics.



来源:https://stackoverflow.com/questions/10207601/how-to-extend-ninject-binding-syntax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!