0

I'm trying to get a handle on DI lately. If I understand everything correctly so far, the main purpose is to write loosely coupled code, to facilitate re-usability. (Also see https://stackoverflow.com/a/9503612/579740)

So far so good, but one thing that's still not entirely clear to me, is where to place the interfaces.

An example tells more then a thousand words:

Library A:

public class A
{
    public A(IInterfaceB b)
    {}
}

Library B:

public interface IInterfaceB
{}

public class B : IInterfaceB
{
    public B (IInterfaceC c)
    {}
}

Library C:

public interface IInterfaceC
{}

public class C : IInterfaceC
{
    public C()
    {}
}

If I place IInterfaceC in Library C, I still have a reference to Library C in Library B. So when I decide to reuse library B, I still need Library C??? Which, in my mind at least, doesn't seem to be loosely coupled...

Can someone explain to me where my thinking is going wrong?

Community
  • 1
  • 1
Koen
  • 2,501
  • 1
  • 32
  • 43

1 Answers1

1
  1. Loose coupled code doesn't always mean loose coupled modules (libraries).
  2. You can achieve loose coupling of modules (libraries) by placing interfaces and implementations in different modules. For example class A is in A.dll, IInterfaceB is in IInterfaceB.dll (and A.dll reference it), class B is in B.dll (and it reference IInterfaceB.dll too)

It looks like following class A -> IInterfaceB <- class B so modules containing class A and class B are not coupled.

  • 1) explains where my thinking is going wrong, but I still don't get where the idea of re usability comes from if the modules are still tightly coupled. And I thought about 2) but it doesn't feel right to put each interface in it's own dll. – Koen Dec 20 '13 at 07:53
  • You should not put each interface in separate dll. You should think in terms of layers. And each layer should have its own SomeLayer.Contracts.dll (with interfaces, exceptions and data transfer objects) and SomeLayer.Implementation.dll (with concrete intarface implementations). You can read about it in depth here - http://www.objectmentor.com/resources/articles/dip.pdf – Oleksandr Kobylianskyi Dec 20 '13 at 10:00
  • This makes a bit more sence :-) Guess I have to make a switch in my head regarding this DI stuff as I had to do regrading referencing every project in my GUI (where [this]( http://stackoverflow.com/a/9503612/579740) helped a lot. – Koen Dec 20 '13 at 11:24
  • @OleksandrKobylianskyi - That PDF link is dead. :*( – bubbleking May 28 '17 at 19:39