FMM*_*FMM 10 .net c# dependency-injection ninject ioc-container
我有一个界面:
public interface IService
{
void DoStuff(int parm1, string parm2, Guid gimmeABreakItsAnExampleK);
}
Run Code Online (Sandbox Code Playgroud)
我想配置Ninject(v3)绑定,以便我可以有一个"调度程序"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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我看起来像这样的绑定最终会在运行时抛出异常,表明存在循环依赖:
this.Bind<IService>().To<DispatcherService>();
this.Bind<IService>().To<SomeOtherService>()
.WhenInjectedExactlyInto<DispatcherService>();
this.Bind<IService>().To<YetAnotherService>()
.WhenInjectedExactlyInto<DispatcherService>();
Run Code Online (Sandbox Code Playgroud)
这可能吗?如果是这样,我做错了什么?忍者可以逃脱这种周期性的依赖厄运吗?
如果您的调度程序是唯一一个将 IService 列表作为参数的 IService,那么这确实有效(我测试过):
kernel.Bind<IService>().To<DispatcherService>().When(x => x.IsUnique);
this.Bind<IService>().To<SomeOtherService>()
.WhenInjectedExactlyInto<DispatcherService>();
this.Bind<IService>().To<YetAnotherService>()
.WhenInjectedExactlyInto<DispatcherService>();
Run Code Online (Sandbox Code Playgroud)
When该子句适用于这种情况的原因是,当构造函数调用服务的单个实例时,IsUnique字段IRequest被设置为。true由于您DispatcherService需要 an IEnumerable,因此该值是false激活 时的值DispatcherService。这可以防止循环依赖的发生。
实际上,告诉内核不要尝试将 DispatcherService 注入自身的任何正确方法都可以工作(这只是一个可能有用的示例)。
编辑:简单地短路循环依赖的更明确的方法似乎是这样的:
kernel.Bind<IService>().To<DispatcherService>().When(
request => request.Target.Member.DeclaringType != typeof (DispatcherService));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
567 次 |
| 最近记录: |