Can injecting addiction prevent cyclic addiction?

Project # 1 has some interfaces and classes that design links # 2.

Now I want to use the implementation of project No. 2 in project No. 1, but vs .net complains about circular dependence.

If I used dependency injection in project No. 1 and became attached to implementation in project No. 2 (since he adheres to the interface contract), will this work, or will I still receive a cyclic dependency error message at runtime?

+3
source share
3 answers

You could probably solve this with DI, but you shouldn't.

If I understood correctly, you have something like this:

  + Assembly A + Assembly B
   |  |
   + - Interface IFoo + - Class ConcreteFoo: IFoo
   |  ^
   + - Class MyClass -> -------> ------- |
In other words, you are trying to get the MyClass ConcreteFoo link, but you cannot, because the assembly B in which ConcreteFoo is located already depends on IFoo in A

This is a design mistake. If you declare an IFoo interface in Assembly A , but no specific implementations, then any other interfaces / classes in assembly A should only reference IFoo , never a specific class that implements it.

There are three ways to eliminate cyclic dependency:

  • Make MyClass dependent on IFoo instead of ConcreteFoo . This is probably the best option if you can do this. If the problem is that you need a physical instance of IFoo for use in MyClass and don’t know where to get it, then you need it to accept IFoo in the constructor - let someone use a MyClass shape outside of which IFoo .

  • Move the interfaces to your assembly. This is still pretty 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 your own assembly. Effectively, the dependency tree will look the same as in Example 2, but if assembly A much smaller than B , this will require less effort.

Hope this helps.

+15
source

You can often solve circular dependency problems with Injection Dependency (DI) using Abstract Factory. See here for an example .

However, although you can solve the problem using DI, it would be better to redesign the API to reduce circular dependency.

You can often break the circular dependency by changing one of the ends of the request-based API to an event-based API.

+8
source

As long as you use only the classes and interfaces from Project 1 in Project 1 code, you'll be fine. (I assume that the configuration for dependency injection is done outside of the project 1 code base.)

But I must also say that the presence of any cyclical dependence should lead you to the question of why it exists, and think about other ways to solve the problem that removes it.

+1
source

Source: https://habr.com/ru/post/1311555/


All Articles