开发者

C# Circular dependencies in Unity with Ctor injection

开发者 https://www.devze.com 2023-04-12 03:08 出处:网络
I kno开发者_高级运维w that the issue of circular dependencies in the contect of dependency injection with prism/unity was dicussed here before.

I kno开发者_高级运维w that the issue of circular dependencies in the contect of dependency injection with prism/unity was dicussed here before.

But I still don't get it. Suppose the following classes:

class Feeder : IFeeder    { 
  IManager _MM, 
  Feeder(IManager MM)
  {
     this._MM = MM;
  }
  public void Start()
  {
  ...
  }
  public void Stop()
  {
  ...
  }
  private Propagate()
  {
     _MM.ConsumeFeed()
  }
};

class FeedManager : IManager
{
   IFeeder _Feeder;
   FeedManager(IFeeder Feeder)
   {
      this._Feeder = Feeder;
   }
   public ConsumeFeed()
   {
   ...
   }
   private Shutdown()
   {
      _Feeder.Stop();
   }
   private StartUp()
   {
      _Feeder.Start();
   }
};

This is clearly a circular dependcy, since Feeder depends on FeedManager and vice verca. I don't see a clear way to resovle this, since it seems a very natural design.

When you follow this link there is a hint to extract some methods but I still don't see how I can decouple those objects. I read about dependency inversion, observer pattern, shared objects, events and so on. To me, this seems all like an overkill to achieve a simple realtionship between the two objects.

Is the only way to resolve this to work with a million events in the application or shared objects? Thanks for help, Juergen


I would make the IFeeder.Propagate method an event the instance of IManager registers to. This way you do not have a circular reference.

Your example here has by the way nothing to do with unity. From my point of view it is more a design issue than an unity issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消