【问题标题】:Implement chain of responsibility in StructureMap在 StructureMap 中实现责任链
【发布时间】:2019-10-14 17:08:44
【问题描述】:

假设我在以下类中实现了责任链设计模式;

interface IDoStuff
{
  IDoStuff Next {get;}

  void Configure();
}

class StepOne
{
  public IDoStuff Next {get; set}

  public StepOne(IDoStuff next)
  {
    Next = next;
  }

  public void Configure()
  {
    // Do configuration relevant to StepOne

    // Call the next configure step in the chain
    Next?.Configure()
  }
}

class StepTwo
{
  public IDoStuff Next {get; set}

  public StepTwo(IDoStuff next)
  {
    Next = next;
  }

  public void Configure()
  {
    // Do configuration relevant to StepTwo

    // Call the next configure step in the chain
    Next?.Configure()
  }
}

我尝试这样配置链

class MyRegistry : Registry
{
  public MyRegistry()
  {
    For<IDoStuff>().Use<StepOne>();
    For<StepOne>().Use(c => new StepOne(c.GetInstance<StepTwo>()));
    For<StepTwo>().Use(c => new StepTwo(null));
  }
}

但是我从 StructureMap 中得到了这个错误;

检测到双向依赖关系! 检查下面的 StructureMap 堆栈跟踪: 1.) IDoStuff (StepOne) 2.) new StepOne(IDoStuff 的默认值) 3.) StepOne 4.) IDoStuff 实例(StepOne) 5.) Container.GetInstance()

注册链的正确方法是什么?

【问题讨论】:

    标签: design-patterns structuremap chain-of-responsibility


    【解决方案1】:

    我想通了。我不需要注册表中的第一行。应该是这样的;

    class MyRegistry : Registry
    {
      public MyRegistry()
      {
        For<IDoStuff>().Use(c => new StepOne(c.GetInstance<StepTwo>()));
        For<StepTwo>().Use(c => new StepTwo(null));
      }
    }
    

    然后链将被构造,如果你这样做container.GetInstance&lt;IDoStuff&gt;(),它会给你一个链StepOne => StepTwo => null

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多