Unity 中的 C# 循环依赖与 Ctor 注入
我知道之前已经讨论过 prism/unity 依赖注入中的循环依赖问题。
但我还是不明白。假设有以下类:
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();
}
};
这显然是一个循环依赖,因为 Feeder 依赖于 FeedManager,反之亦然。我没有看到一个明确的方法来解决这个问题,因为这似乎是一个非常自然的设计。
当您点击此链接 有一个提示可以提取一些方法,但我仍然不知道如何解耦这些对象。 我阅读了有关依赖倒置、观察者模式、共享对象、事件等的内容。 对我来说,这对于在两个对象之间实现简单的关系似乎有些过分了。
解决此问题的唯一方法是处理应用程序或共享对象中的一百万个事件吗? 感谢您的帮助,于尔根
I know 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将使 IFeeder.Propagate 方法成为 IManager 实例注册到的事件。这样就不会出现循环引用。
顺便说一句,你在这里的例子与团结无关。从我的角度来看,这更多的是一个设计问题,而不是一个统一问题。
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.