问题描述
现在我想在Project#1中使用Project#2的实现,但是网络抱怨循环依赖。
如果我在Project#1中使用依赖注入,并绑定到Project#2中的实现(因为它遵守了接口合同),这个工作还是我会在运行时得到循环依赖错误消息?
你可能 / em>用DI解决这个问题,但是你不应该。
如果我理解正确,你有这样的东西:
+大会A +大会B
| |
+ - 接口IFoo + - Class ConcreteFoo:IFoo
| ^
+ - Class MyClass - > -------> ------- |
换句话说,你试图获得 MyClass
来引用 ConcreteFoo
,但是不能因为程序集 B
,其中 ConcreteFoo
居住在,已经取决于 IFoo
在 A
。
这是一个设计错误。如果您在程序集 A
中声明了接口 IFoo
,但没有具体的实现,则汇编程序中的任何其他接口/ code> A 应该仅引用 IFoo
,永不一个具体的类实现它。
有三种方法可以消除循环依赖:
-
Make
MyClass
依赖于IFoo
而不是ConcreteFoo
。这可能是最好的选择,如果你能做到这一点。如果问题是您需要在MyClass
中使用的IFoo
的实体实例,并且不知道从哪里获取一个来自,然后在构造函数中使用IFoo
,让谁使用MyClass
找出什么IFoo
使用。 -
将界面移动到自己的程序集中。这仍然是一个相当不错的做法。您的设计将如下所示:
+ Assembly App + Assembly Interfaces + Assembly Concrete
| | |
| + - 接口IFoo |
| | \ |
+ - MyClass类\ ------ + - Class ConcreteFoo
| | | ^
+ ----会员Foo - > ---------------------> -------------- ----- |
-
将
MyClass
移动到自己的程序集中。有效地,您的依赖关系树将与上述#2看起来一样,但是如果程序集A
比B
小得多这将需要较少的努力。
希望有所帮助。
Project#1 has some interfaces and classes that project#2 references.
Now I want to use the implementation of Project#2 in Project#1 but vs.net complains about a circular dependency.
If I was to use dependancy injection in Project#1 and bind to the implementation in Project#2 (since it adheres to the interface contract), will this work or I will still get the circular dependency error message at runtime?
You probably could solve this with DI, but you shouldn't.
If I understand correctly, you have something like this:
+ Assembly A + Assembly B | | +-- Interface IFoo +-- Class ConcreteFoo : IFoo | ^ +-- Class MyClass -->------->-------|
In other words, you're trying to get MyClass
to reference ConcreteFoo
, but you can't because assembly B
, which ConcreteFoo
resides in, already depends on IFoo
in A
.
This is a design error. If you declare the interface IFoo
in Assembly A
, but no concrete implementations, then any other interfaces/classes in assembly A
should only reference IFoo
, never a concrete class that implements it.
There are three ways to eliminate the circular dependency:
Make
MyClass
dependent onIFoo
instead ofConcreteFoo
. This is probably the best option if you can do it. If the issue is that you need a physical instance ofIFoo
for use inMyClass
and don't know where to get one from, then have it take anIFoo
in the constructor - let whoever usesMyClass
figure out whatIFoo
to use.Move the interfaces to their own assembly. This is still a reasonably good practice. Your design will look like this:
+ Assembly App + Assembly Interfaces + Assembly Concrete | | | | +-- Interface IFoo | | | \ | +-- Class MyClass | \------+-- Class ConcreteFoo | | | ^ +---- Member Foo ->--------------------->-------------------|
Move
MyClass
to its own assembly. Effectively your dependency tree will look the same as in #2 above, but if assemblyA
is much smaller thanB
then this would require less effort.
Hope that helps.
这篇关于依赖注入可以防止循环依赖吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!