我想弄清楚如何用ninject绑定类似这样的东西的正确方法。与ninject的循环依赖关系
interface IMainService
{
void DoStuff();
}
interface IOtherService
{
void DoSomeMagic();
}
abstract class BaseClass
{
//many stuff here
}
class MainClass : BaseClass, IMainService
{
public MainClass(IOtherService s)
{
}
public void DoStuff()
{
throw new NotImplementedException();
}
//do many other things
}
class OtherClass : IOtherService
{
public OtherClass(IMainService s)
{
}
public void DoSomeMagic()
{
throw new NotImplementedException();
}
}
class BaseModule : NinjectModule
{
public override void Load()
{
Bind<MainClass>().To<MainClass>();
Bind<IMainService>().To<MainClass>();
Bind<IOtherService>().To<OtherClass>();
}
}
static class Program
{
static void Main()
{
var kernel = new StandardKernel(new BaseModule());
var main = kernel.Get<MainClass>();
}
}
这让我异常:
Error activating IOtherService using binding from IOtherService to OtherClass
A cyclical dependency was detected between the constructors of two services.
Activation path:
4) Injection of dependency IOtherService into parameter s of constructor of type MainClass
3) Injection of dependency IMainService into parameter s of constructor of type OtherClass
2) Injection of dependency IOtherService into parameter s of constructor of type MainClass
1) Request for MainClass
Suggestions:
1) Ensure that you have not declared a dependency for IOtherService on any implementations of the service.
2) Consider combining the services into a single one to remove the cycle.
3) Use property injection instead of constructor injection, and implement IInitializable if you need initialization logic to be run after property values have been injected.
我不知道怎么写BaseModule。我只需要一个MainClass实例和一个OtherClass实例(如单例)。
我想这样的事情:
Bind<MainClass>().To<MainClass>().InSingletonScope();
Bind<IMainService>().To<MainClass>().InRequestScope();
Bind<IOtherService>().To<OtherClass>().InSingletonScope();
但随着同样的错误。
以及如何编写仅使用MainClass和IMainService接口的一个实例的绑定?
感谢您的回答。
感谢在t他的小费。我发现了财产注入的完美解决方案。但它没有IOtherService OtherService {set; }在IMainServices上,因为当我用[Inject]装饰属性时,Ninject自己添加正确的实例。 – 2010-08-18 13:57:01
这不起作用。使用Ninject的最新版本时,如果您对两者都使用属性注入,它将抛出一个'StackOverflowException',并且如果只有一个使用属性注入(和另一个构造函数注入),将抛出“检测到周期性依赖关系”。 – 2012-08-15 14:23:04
啊,但只要您使用的是非暂时性作用域(默认)的作用域,它*就会工作。 – 2012-08-16 00:57:16