Koen
Koen

Reputation: 2571

Dependency Injection - Loosely coupled code - Interfaces

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?

Upvotes: 0

Views: 170

Answers (1)

Oleksandr Kobylianskyi
Oleksandr Kobylianskyi

Reputation: 3380

  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.

Upvotes: 1

Related Questions