GW2.NET icon indicating copy to clipboard operation
GW2.NET copied to clipboard

Stop using poor man's dependency injection

Open SamHurne opened this issue 8 years ago • 0 comments

[Moved from Codeplex: https://gw2dotnet.codeplex.com/workitem/1346]

While most of the library accepts dependencies as constructor parameters, there are a lot of constructor overloads that create their own objects.

This "technique" is called poor man's dependency injection. Code written like this is only acceptable in the top-level library (GW2NET.csproj).

When you see code like this, refactor it so that there is only 1 constructor that has parameters for every dependency.

class Foo
{
    private readonly IBar bar;

    public Foo()
        : this(new BarImplementation())
    {
    }

    public Foo(IBar bar)
    {
        this.bar = bar;
    }
}

Refactored without poor man's dependency injection:

class Foo
{
    private readonly IBar bar;

    public Foo(IBar bar)
    {
        this.bar = bar;
    }
}

StevenLiekens wrote May 27 at 4:24 PM

Example changeset: https://gw2dotnet.codeplex.com/SourceControl/changeset/40883

StevenLiekens wrote May 28 at 7:52 AM

Recommended reading: https://stackoverflow.com/questions/7099406/what-is-the-real-difference-between-bastard-injection-and-poor-mans-injectio

SamHurne avatar Sep 19 '15 15:09 SamHurne