c# - 接口(interface)的调度程序实现的 Ninject 绑定(bind)

标签 c# .net dependency-injection ninject ioc-container

我有一个界面:

public interface IService
{
    void DoStuff(int parm1, string parm2, Guid gimmeABreakItsAnExampleK);
}

我想配置 Ninject (v3) 绑定(bind),这样我就可以有一个“调度程序”shuffle 方法调用多个 IService 实例,如下所示:

public sealed class DispatcherService : IService
{
    private IEnumerable<IService> _children;

    public DispatcherService(IEnumerable<IService> children)
    {
        this._children = children.ToList();
    }

    public void DoStuff(int parm1, string parm2, Guid gimmeABreakItsAnExampleK)
    {
        foreach(var child in this._children)
        {
            child.DoStuff(parm1, parm2, gimmeABreakItsAnExampleK);
        }
    }
}

但是,我的绑定(bind)看起来像这样,最终会在运行时抛出一个异常,指示循环依赖:

this.Bind<IService>().To<DispatcherService>();

this.Bind<IService>().To<SomeOtherService>()
    .WhenInjectedExactlyInto<DispatcherService>();
this.Bind<IService>().To<YetAnotherService>()
    .WhenInjectedExactlyInto<DispatcherService>();

这可能吗?如果是这样,我做错了什么?忍者能否摆脱这种周期性的依赖厄运?

最佳答案

如果您的调度程序是唯一 IService,它会将 IServices 列表作为参数,这确实有效(我测试过):

kernel.Bind<IService>().To<DispatcherService>().When(x => x.IsUnique);
this.Bind<IService>().To<SomeOtherService>()
    .WhenInjectedExactlyInto<DispatcherService>();
this.Bind<IService>().To<YetAnotherService>()
    .WhenInjectedExactlyInto<DispatcherService>();

When 子句适用于这种情况的原因是 IRequestIsUnique 字段设置为 true 当您的构造函数调用服务的单个实例时。由于您的 DispatcherService 调用 IEnumerable,因此在激活 DispatcherService 时值为 false。这可以防止循环依赖的发生。

实际上,任何告诉内核不要尝试将 DispatcherService 注入(inject)自身的正确方法都可行(这只是一个可能有用的示例)。

编辑:简单地短路循环依赖的更明确的方法似乎是这样的:

kernel.Bind<IService>().To<DispatcherService>().When(
   request => request.Target.Member.DeclaringType != typeof (DispatcherService));

关于c# - 接口(interface)的调度程序实现的 Ninject 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12847070/

相关文章:

c# - System.Data.Common.DbDataReader.ReadAsync 中的异步是什么?

c# - 无法加载 configProtectedData 提供程序

unit-testing - 依赖注入(inject)和单元测试此构造函数

javascript - $http 依赖注入(inject)抛出错误

c# - 在 XNA 中调整和加载 texture2d

c# - 如何在 asp.net 中的按钮单击事件调用之前和之后调用 javascript 函数

.net - 经典 ADO.NET - 有人还在使用它吗?

c# - Full outer join,在 2 个数据表上,带有列列表

Android Dagger2 + OkHttp + Retrofit 依赖循环错误

c# - 在您的应用程序中加载任何页面时是否有调用的函数?