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?

Nandini Singhal
  • 131
  • 3
  • 8

1 Answers1

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
ddfra
  • 2,413
  • 14
  • 24