5

I am confused about dependency injection in .NET Core where I have many intercoupled dependencies. I have a class MyClass implementing an interface IMyClass as follows:

public class MyClass : IMyClass
{
     private IClass classA;
     private IClass classB;

     public MyClass (ClassA classA, ClassB classB)
     {
          this.classA = classA;
          this.classB = classB;
     }
     ....
}

The classes ClassA and ClassB are implementations of interface IClass as follows:

public class ClassA : IClass
{
     public ClassA (many other DI)
     {
     }
}

public class ClassB : IClass
{
     private IClass baseClass;

     public ClassB (IClass baseClass, ...)
     {
          this.baseClass = baseClass;
          ....
     }
}

In my startup file, how should I register my dependencies. I have tried the following, which doesn't work:

services.AddSingleton<ClassA>();
services.AddSingleton<IMyClass, MyClass>();

Can someone please explain what is the issue here and the solution to this?

5
  • You have to register ClassB too. Commented Jul 13, 2020 at 16:26
  • 1
    We need the last piece of the puzzle: how do you use ClassA and ClassB? do you use both of them as dependencies? Do you want ti use only ClassB as Decorator of ClassA? Commented Jul 13, 2020 at 16:27
  • that doesn't work either Commented Jul 13, 2020 at 16:27
  • we want to use both of them Commented Jul 13, 2020 at 16:28
  • see my answer stackoverflow.com/a/77248536/836376 Commented Oct 7, 2023 at 11:05

1 Answer 1

5

you need to add the following in configureservices of Startup.cs:

var factory = ActivatorUtilities.CreateFactory(typeof(ClassB), new Type[] {typeof(IClass)});
services.AddSingleton<ClassB>(sp => factory.Invoke(sp, new object[] {sp.GetService<ClassA>()}) as ClassB); //when calling sp.GetService<ClassA> you can of course pass any implementation of IClass instead of ClassA. Of course you cannot pass ClassB beacause of infinite recursion.

With this solution you are telling the IoC container that you want to register a service for ClassB wich:

  • will have his dependency of type "IClass" resolved as "ClassA" as it was declared in the IoC container
  • will have all other dependencies normally resolved by the IoC container
Sign up to request clarification or add additional context in comments.

1 Comment

this is a little complex, but thanks a lot! this worked. I am trying to understand this more :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.