vendredi 9 septembre 2016

How to improve dependecy injection (architecture of my interfaces-classes)?

Imagine I have this classes:

public class MyClass : IMyClass
{
    private readonly ISomething1 _something1;
    private readonly ISomething2 _something2;

    public MyClass(ISomething1 something1, ISomething2 something2)
    {
        _something1 = something1;
        _something2 = something2;
    }

    public SomeObject Get(AnotherObject anotherObject)
    {
        var a = _something1.Calculate(anotherObject.Property1);
        var b = _something2.Get(anotherObject.Property2, a);

        return b;
    }
}

public class MyClass2 : IMyClass
{
    private readonly ISomething1 _something1;
    private readonly ISomething2 _something2;

    public MyClass(ISomething1 something1, ISomething2 something2)
    {
        _something1 = something1;
        _something2 = something2;
    }

    public SomeObject Get(AnotherObject anotherObject)
    {
        var a = _something1.Calculate(anotherObject.Property1);
        var b = _something2.Get(anotherObject.Property2, a);

        return b;
    }
}

It looks like MyClass and Myclass2 are very similar. However, the difference is that I am injecting different implementations of ISomething1 and ISomething2 for these classes using Ninject:

//MyClass
Bind<ISomething1>().To<AmazingSomething>().WhenInjectedInto<MyClass>();
Bind<ISomething2>().To<BeautifulSomething>().WhenInjectedInto<MyClass>();

//MyClass2
Bind<ISomething1>().To<GoodSomething>().WhenInjectedInto<MyClass2>();
Bind<ISomething2>().To<UglySomething>().WhenInjectedInto<MyClass2>();

I don't like this solution because it violates DRY principle. However, I like it because it is following Open/closed principle (I hope so).

Is there a better way to accomplish my goal?

Aucun commentaire:

Enregistrer un commentaire