I was reading the dependency inversion principle. It states that the module should be dependent on abstraction. I understand most of the parts, and I can apply them. There is one place where there is confusion.
Whenever we call a dependent class method. We sometimes pass parameter as an object. And this object needs to be instantiated and pass as parameter
Entity.cs
public class Entity
{
public string Prop1 {get; set;}
public string Prop2 {get; set;}
}
ClientClass.cs
public class ClientClass
{
private readonly IDependentClass _dep;
public ClientClass(IDependentClass dep)
{
_dep = dep;
}
public void Method()
{
var e = new Entity();
_dep.Method(e)
}
}
DependentClass.cs
public class DependentClass: IDependentClass
{
public void Method(Entity e)
{
}
}
Here the Entity class is just a data transfer object. But it has a concrete dependency on ClientClass and DependentClass which violates the DIP. Is my understanding correct? How to fix this?
you can create interface IEntity too to follow DI principles
but as @Nicosi noticed in this case you will not gain much with IEntity interface. I makes sense only if you have any methods too and you can use polymorphism and Liskov substitution Principle (LSP) with DI together.
I don't see much sense using
inside of Method() since you create an empty object and breaking DI too
Try this
another way to use DI could be
But it looks funny for me