【问题标题】:How to extend Ninject Binding Syntax如何扩展 Ninject 绑定语法
【发布时间】:2012-04-18 10:34:30
【问题描述】:

有没有办法扩展现有的绑定语法(例如扩展方法),让我们有这样的东西:

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

【问题讨论】:

  • 我通常使用 Bind(typeof(IRepository)).To(typeof(MyRepository));您希望这种绑定如何发生
  • WhenCustom 应该做什么?你能给出(例子或用散文解释)你的条件应该包括和排除的正面和负面案例吗?

标签: ninject


【解决方案1】:

IBindingWhenSyntax&lt;T&gt; 编写一个扩展方法,并使用现有的When 重载来实现您的逻辑:

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

【讨论】:

  • 对不起,我没有早点回到这个,这是我需要的例子 - 在 Ninject 中有一个 WhenInjectedInto 方法所以我需要类似的东西,我需要能够获得标准语法,但也获得自定义类型,例如codeIBindingInNamedWithOrOnSyntaxWhenInjectedInto()code。这里的主要问题是我需要使用扩展方法创建它,然后由于 TParent 的原因我无法访问 T 类型。目前我使用 语法并且它不是那么可读。还有其他方法吗?谢谢
【解决方案2】:

重新定义问题(以与您的评论保持一致)您想要创建一个具有类似于以下签名的扩展;

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

很遗憾,我们没有使用“纯”泛型进行扩展的奢侈。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多