可以依赖注入prevent循环依赖? [英] Can dependency injection prevent a circular dependency?
问题描述
项目#1有一些项目#2引用接口和类。
现在我想用工程#2#项目1的实施,但vs.net抱怨循环依赖。
如果我是使用在项目#1依赖关系注入和绑定到项目#2的实现(因为它符合接口的合同),将这项工作或我仍然会得到循环依赖错误消息,在运行时<? / p>
您也许可以的通过DI解决这个问题,但你的不应该的
如果我理解正确的话,你有这样的事情:
大会+ A +组件B
| |
+ - 接口IFoo的+ - 类ConcreteFoo:IFoo的
| ^
+ - MyClass类 - > -------> ------- |
在换句话说,你正在试图获得 MyClass的
引用 ConcreteFoo
,但你不能因为装配 B
,其中 ConcreteFoo
驻留在已经依赖于的IFoo
在 A
。
这是一个设计错误。如果声明在大会接口的IFoo
A
,但没有具体的实现,那么任何其他接口/装配类 A
应的仅参考的IFoo
,绝不会的具体类实现它。
有三种方法可以消除循环依赖:
-
请
MyClass的
依赖的IFoo
而不是ConcreteFoo
。这可能是最好的选择,如果你能做到这一点。如果问题是,你需要的IFoo
使用的物理实例MyClass的
,不知道从哪里得到一个来自,然后把它取一个的IFoo
在构造 - 让谁使用MyClass的
找出的IFoo
使用。 -
移动接口,以自己组装。这仍然是一个相当不错的做法。你的设计是这样的:
+应用大会大会+接口+混凝土装配
| | |
| + - 接口的IFoo |
| | \\ |
+ - MyClass类| \\ ------ + - 类ConcreteFoo
| | | ^
+ ----会员美孚 - > ---------------------> ------------------- |
- 将
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.
这篇关于可以依赖注入prevent循环依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!