GU0007
November 24, 2021 ยท View on GitHub
Prefer injecting
| Topic | Value |
|---|---|
| Id | GU0007 |
| Severity | Hidden |
| Enabled | False |
| Category | Gu.Analyzers.Correctness |
| Code | GU0007PreferInjecting |
Description
Prefer injecting.
Motivation
This is an analyzer that can be helpful if you refactoring legacy code to use an IoC-container. This analyzer is expensive and you probably only want to enable it when refactoring. It changes references that are newed up to be injected. Candidates for injection are:
- Not in namespace
System - Reference types
- With empty ctor or only ctor arguments that are injected.
Sample code before:
public class Foo
{
private readonly Bar bar;
public Foo()
{
this.bar = new Bar();
}
}
public class Bar
{
}
Remarks:
Useful when refactoring to using IoC-container. Remarks: There is an UNSAFE version of the code fix that handles:
public class Meh : Foo
{
public Meh(Baz baz)
: base(baz.Bar)
{
}
}
and changes it to:
public class Meh : Foo
{
public Meh(Baz baz, Bar bar)
: base(bar)
{
}
}
This is for cleaning up service locator messes.
How to fix violations
Use the code fix or manually change the code to pass in the reference via ctor. The above sample becomes:
public class Foo
{
private readonly Bar bar;
public Foo(Bar bar)
{
this.bar = bar;
}
}
public class Bar
{
}
Configure severity
Via ruleset file.
Configure the severity per project, for more info see MSDN.
Via #pragma directive.
#pragma warning disable GU0007 // Prefer injecting
Code violating the rule here
#pragma warning restore GU0007 // Prefer injecting
Or put this at the top of the file to disable all instances.
#pragma warning disable GU0007 // Prefer injecting
Via attribute [SuppressMessage].
[System.Diagnostics.CodeAnalysis.SuppressMessage("Gu.Analyzers.Correctness",
"GU0007:Prefer injecting",
Justification = "Reason...")]