How to properly add dependecy of entity class to other classes and reduce coupling

81 Views Asked by At

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?

1

There are 1 best solutions below

7
Serge On

you can create interface IEntity too to follow DI principles

public interface IEntity
{
     string Prop1 {get; set;}
    string Prop2 {get; set;}
}

public class DependentClass: IDependentClass
{
    public void Method(IEntity e)
    {
    }
}

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

 var e = new Entity();

inside of Method() since you create an empty object and breaking DI too

Try this

public class ClientClass
{
    private readonly IDependentClass _dep;
    public ClientClass(IDependentClass dep)
    {
         _dep = dep;
    }
    public void Method(IEntity e)
    {
      
         _dep.Method(e)
    }
}

another way to use DI could be

public class ClientClass
{
    private readonly IDependentClass _dep;
    private readonly IEntity _ent;

    public ClientClass(IDependentClass dep, IEntity ent)
    {
         _dep = dep;
        _ent=ent;
    }
    public void Method()
    {
      
         _dep.Method(_ent);
    }
}

But it looks funny for me