Я пытаюсь найти правильный способ связать что-то вроде этого с 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?
Спасибо за ответы.
Спасибо за т его наконечник. Я нашел идеальное решение с инъекцией свойств. Но это без IOtherService OtherService {set; } в IMainServices, потому что, когда я украшаю свойство с помощью [Inject], Ninject добавляет к нему правильный экземпляр. –
Это не работает. В последней версии Ninject он будет вызывать 'StackOverflowException', если вы используете инъекцию свойств для обоих, и будет генерировать« циклическую зависимость », если только один использует инъекцию свойств (и другую инъекцию конструктора). –
Ах, но он * делает * работать до тех пор, пока вы используете область, отличную от временной области (по умолчанию). –