c# – 与ninject的循环依赖

前端之家收集整理的这篇文章主要介绍了c# – 与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接口的一个实例的绑定?

感谢您的答案.

解决方法

错误消息所示,您在MainClass和OtherClass之间具有循环依赖关系,因为您无法创建一个没有另一个的实例.理想情况下,您应该重组您的类层次结构以消除此需求.

如果您不能,解决方案是为一个(或两个)类使用属性注入,例如.

public interface IMainService
{
    void DoStuff();
    IOtherService OtherService { set; }
}

public class MainClass
{
    public IOtherService OtherService { get; set; }
    public void DoStuff() { ... }
}

public class OtherService
{
    public OtherService(IMainService main)
    {
        main.OtherService = this;
    }
}
原文链接:https://www.f2er.com/csharp/94244.html

猜你在找的C#相关文章