3

So I use windsor dependency injection:

container.Register(Component.For<IX>().ImplementedBy<X>().LifestyleSingleton());

My problem (such as it is) is that in the X class's constructor, I cannot easily see that that constructor is used. In fact, Visual Studio tells me that it is not in use:

0 references

This is mildly annoying - it becomes difficult to spot dead code.

How do you fix this?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
iakob
  • 309
  • 1
  • 6

1 Answers1

4

There is nothing to fix.

The constructor is invoked by the container to initialize the object when being resolved.

IX x = container.Resolve<IX>();

Thus Visual Studio wont see any explicit calls to that constructor from the code.

Ideally, the target class should only have one constructor following explicit dependencies principle.

public class X : IX {
    private readonly IDependency dependency;

    public X(IDependency dependency) {
        this.dependency = dependency;

        //...
    }

    //...
}

This will ensure that the lone constructor is the one used by the container when resolving the class.

If one is actively testing their code or is following TDD, then there should be references to the used code in supporting tests.

[TestMethod]
public void X_Should_Do_Something() {
    // Arrange

    //...

    IX subject = new X(...);

    // Act
    var result = subject.SomeMember();

    // Assert
    //...
}

where explicit calls are used to arrange the subject under test.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • _"If one is actively testing their code or is following TDD, then there should be references to the used code in supporting tests"_ Even if you have no tests at all, you'll always still have a reference to the concrete class class in your dependency registration (e.g. `services.AddTransient()` or in OP's case `.ImplementedBy()`) – Flater Jun 23 '20 at 13:31
  • @Flater yes but in OP case they were referring to the fact that the class constructor had no references. – Nkosi Jun 23 '20 at 13:34
  • Good point, I had misread your last paragraph. I'm just weary of focusing on constructor usage to find dead code as it's so easy to lead to false positives (e.g. the windsor example in the question) or false negatives (e.g. dead factories which reference the constructor). – Flater Jun 23 '20 at 13:38
  • @Flater I agree. – Nkosi Jun 23 '20 at 13:41