有没有办法扩展现有的绑定语法(例如扩展方法),这将允许我们有这样的东西:
Bind<IRepository>().ToProvider<MyProvider<MyRepository>>().WhenCustom<SomeType>()
答案 0 :(得分:2)
为IBindingWhenSyntax<T>
编写扩展方法,并使用现有的When
重载来实现您的逻辑:
class BindingWhenExtensions
{
public IBindingInNamedWithOrOnSyntax<T> WhenCustom<T>(
this IBindingWhenSyntax<T> syntax)
{
return syntax.When(r => true);
}
}
答案 1 :(得分:0)
重新构建问题(与评论一致)您想要创建一个类似于以下签名的扩展程序;
public static IBindingInNamedWithOrOnSyntax<T> WhenCustom<TParent>(
this IBindingWhenSyntax<T> binding)
据我所知,我们无法像Ninject一样干净利落地扩展,因为正如你正确地提到T
这里定义的on an interface是我们的扩展所不知道的。
所以我们的扩展签名必须是;
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);
令人遗憾的是,我们没有“纯粹”泛型的延伸。