问题
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