csharpsquid:S1312 - False Positive for injected Loggers in DI?

  • What language: C#
  • Which rule: S1312 Logger fields should be “private static readonly”
  • Why do you believe it’s a false-positive/false-negative: Since the upgrade to 10.6 all of our classes that have a Logger injected have this finding. As the field gets injected by the constructor it is not possible to make it static. In the rule the comment states " This rule should be activated when Service Locator Design pattern is followed in place of Dependency Injectionfor logging." We are not using the Service Locator Design Pattern.
  • using
    • SonarQube - 10.6
    • SonarLint - 8.1.0 which Visual Studio 2022 Enterprise 17.9.6
      • in connected mode with SonarQube
  • How to reproduce the problem:
    Create a class MyDiClass1, as such:
using Microsoft.Extensions.Logging;

namespace SonarQubeTest;

public class MyDiClass1
{
	private readonly ILogger<MyDiClass1> _logger;

	public MyDiClass1(ILogger<MyDiClass1> logger)
	{
		_logger = logger;
	}

	public void SomeMethod()
	{
		_logger.LogTrace("Sample");
	}

}

Run the scan and get the result

By the way it is of course not possible to change it to static, otherwise you’ll get CS0198

Looks like a False-Positive to me

1 Like

Hello Dominik,

S1312 is not activated in the default quality profile. The documentation states that This rule should be activated when Service Locator Design pattern is followed.
The rule is designed to be helpful in projects that exclusively use the service locator pattern.

As you pointed out, the rule doesn’t make sense in constructor dependency injection scenarios. Therefore, you should deactivate the rule for your project.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.