Dependency injection toolset upgrade

Akos Nagy
May 21, 2018

Dependency injection is probably the best thing in software development since slide bread. I often blog about related things and I also have a Visual Studio extension to help those who apply the principles in practice.

Guard clauses in constructors

An important piece of best-practice is that whenever you use constructor injection, you should check your arguments for null values (after all, constructor injection is best used for required dependencies). This is known as a guard clause:

public class MyService
  private readonly IDependency dependency;
  public class MyService(IDependency dependency)
    if (dependency == null)
      throw new ArgumentNullException("dependency");
     this.dependency = dependency;

My VS extension did not account for this best practice unfortunately. A user of the toolset was kind enough to point this out on Github, and I totally agree that this should be part of constructor.

So now, you can use my extension from the marketplace to generate constructors that take this into consideration:

Obviously this could be made a lot better with the features of "new-generation" C#: the nameof operator of C# 6 and throw expression from C# 7. Unfortunately, I have not found any way to determine the proejct language version from inside a CodeRefactoringProvider. I went to Stackoverflow and asked a question about it, but no definite answer for now. If you have any ideas, feel free to join the discussion there or at Github, or even issue a PR yourself.

And of course, download the tool ;)

Akos Nagy