Is there a benefit implementing interfaces explicitly with respect to Dependency Injection?
As far as I understand, interfaces can be implemented either explicitly or implicitly:
interface IFoo
{
void Bar();
}
//implicit implementation
class Foo1 : IFoo
{
public void Bar(){}
}
//explicit implementation
class Foo2 : IFoo
{
void IFoo.Bar(){}
}
Now the explicit implementation can only be called by calling the interface method, while the implicit implementation can be called directly on an instance of the class:
class Baz
{
void Ba()
{
Foo1 foo1 = new Foo1();
foo1.Bar();
Foo2 foo2 = new Foo2();
foo2.Bar(); //syntax error
IFoo foo2_explicit = new Foo2();
foo2_explicit.Bar();
}
}
Thus, using explicit interface implementations, one cannot accidentally call a method on a concrete class, but one has to call the interface method. Does this prevent tightly coupled code as is one purpose of DI or am I barking up the wrong tree here? After all, one cannot accidently write a constructor or method that gets a concrete class injected instead of an interface:
class Baz
{
void Ba(Foo2 foo)
{
foo.Bar(); //syntax error
}
void Bb(IFoo foo)
{
foo.Bar();
}
}