Shaun Luttin Shaun Luttin - 18 days ago 5x
C# Question

Does injecting a generic interface with concrete types defeat the purpose of dependency injection?

Consider the following scenario.

public interface IRestaurant<IDinner, IDesert> { }

public class Pasta : IDinner {}
public class Cake : IDesert {}

public class Chef
// resolving a mix of interfaces and concrete classes
public Chef(IRestaurant<Pasta, Cake>) { }

Does the injection of two concrete classes defeat the purpose of dependency injection? My sense is that it does, because we are now strongly coupled to the
classes whereas dependency injection is there to break that coupling.

Would the following make more sense?

public class Chef<IDinner, IDesert>
public Chef(IRestaurant<IDinner, IDesert>) { }


I think you are mixing concepts here- DI doesn't inherently have anything to do whether you use interfaces or concrete classes per se. You could (for example) inject a concrete class that was one of several subclasses of Pasta (Linguini, Ravioli, etc)., and the benefits of DI (low coupling, discrete testability) still apply.

Most people use interfaces because that further lowers the coupling to the specific interface you need, without implying any implementation (for example, maybe it doesn't make sense to have GlutenFreeElbowNoodles inherit from Pasta) but that isn't really an IoC concern.