Ninject:将父实例提供给正在解析的子实例
我有这个类层次结构:
public interface ISR { }
public interface ICU { }
public interface IFI { }
public class CU : ICU { }
public class SR : ISR
{
public SR(IFI fi)
{
FI = fi;
}
public IFI FI { get; set; }
}
public class FI : IFI
{
public FI(ISR sr, ICU cu)
{
SR = sr;
CU = cu;
}
public ISR SR { get; set; }
public ICU CU { get; set; }
}
public class Module : NinjectModule
{
public override void Load()
{
Bind<ISR>().To<SR>();
Bind<ICU>().To<CU>();
Bind<IFI>().To<FI>();
}
}
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel(new Module());
var sr = kernel.Get<ISR>();
}
}
当我运行此代码时,出现异常,因为我有循环依赖项。 SR类需要注入一个IFI实例才能完成,FI类需要注入一个ISR实例才能完成。
当然,使用属性注入并不能解决这个问题。
但我有一个特殊性:我需要首先构建 ISR,并且必须将此实例提供给 FI。因此 ISR 和 IFI 需要共享一个范围。
你会如何用 Ninject 解决这个问题?
I have this class hierarchy:
public interface ISR { }
public interface ICU { }
public interface IFI { }
public class CU : ICU { }
public class SR : ISR
{
public SR(IFI fi)
{
FI = fi;
}
public IFI FI { get; set; }
}
public class FI : IFI
{
public FI(ISR sr, ICU cu)
{
SR = sr;
CU = cu;
}
public ISR SR { get; set; }
public ICU CU { get; set; }
}
public class Module : NinjectModule
{
public override void Load()
{
Bind<ISR>().To<SR>();
Bind<ICU>().To<CU>();
Bind<IFI>().To<FI>();
}
}
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel(new Module());
var sr = kernel.Get<ISR>();
}
}
When I run this code, I have an exception because I have a cyclic dependency. The SR class needs an instance of IFI to be injected in order to be completed, and the FI class needs an instance of ISR to be injected.
Of course, using a property injection doesn't solve this issue.
I have a particularity though: I need ISR to be constructed first, and it is this instance which must be given to FI. So ISR and IFI need to share a scope.
How would you solve that with Ninject?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
处理这个问题的最好方法是重构你的设计以消除循环依赖。几乎所有的循环依赖都可以通过适当的设计来消除。如果存在循环依赖,通常存在设计缺陷。您很可能没有履行单一职责原则。
否则,您必须进行双向属性注入并确保它们具有相同的范围。例如,来自 NamedScope 扩展的 InCallScope。请参阅http://www.planetgeek。 ch/2010/12/08/如何使用-additional-ninject-scopes-of-namedscope/
The best way to handle this problem is to refactor your design to remove the cyclic dependency. Almost all cyclic dependencies can be removed with a proper design. If you have cyclic dependencies there is usually a design flaw. Most likely you do not fulfill the Single Responsibility Principle.
Otherwise you have to do two way property injection and ensure they have the same scope. E.g. InCallScope from the NamedScope extension. See http://www.planetgeek.ch/2010/12/08/how-to-use-the-additional-ninject-scopes-of-namedscope/