-1

I am using .net core for the Dependency Injection to instantiated the class.

class A : InterfaceA { } and class B : InterfaceA { }

StartUp.cs:

_service.AddTransient(InterfaceA, classA)
_service.AddTransient(InterfaceA, classB)

Controller.cs:

public ConstructorA (InterfaceA service) { }

How to tell it uses classA or classB in the ConstructorA?

LittleFunny
  • 8,155
  • 15
  • 87
  • 198

2 Answers2

1

I dont think so your code will work. But you can try like below.

In StartUp :

services.AddSingleton<classA>();  
services.AddSingleton<classB>();  


services.AddTransient<Func<string, InterfaceA>>(serviceProvider => key =>  
{  
   switch (key)  
     {  
       case "A":  
           return serviceProvider.GetService<classA>();  
       case "B":  
           return serviceProvider.GetService<classB>();  
       default:  
           throw new KeyNotFoundException();  
            }  
        });

In Caller method :

public class Caller: ICaller  
{  
    private readonly Func<string, InterfaceA> _injector;  
    public Caller(Func<string, InterfaceA> injector)  
    {  
        this._injector = injector;  
    }  

    public object Get()  
    {  
        return _injector("A").GetData();  
    }  
} 
Manjunatha DL
  • 286
  • 3
  • 11
0

Why you create a class that have classA and classB for DI ? I think you can create a concreteModel for ClassA and ClassB. Than you can inject this complex model with InterfaceA ?

OmerAkgun
  • 34
  • 3