Search code examples
c#dependency-injection.net-6.0

Pass the type of the requesting class to the dependency injected class in .NET 6?


How do I do the following code, but instead of x.GetType() which returns ServiceProviderEngineScope it returns the requesting class's type (e.g., HomeController).

builder.Services.AddScoped<IMyService>((IServiceProvider x) => new MyService(x.GetType()));

To try and clarify a little more,

public class HomeController
{
    private readonly IMyService MyService;

    // I want HomeController's type to be passed to the instance of IMyService since it's the class requesting it.
    public HomeController(IMyService myService) 
    {
         MyService = myService;
    }
}

MyService would look something like this:

public class MyService : IMyService
{
    public MyService(Type requestingType)
    {
        Console.WriteLine($"This service was requested by {requestingType.Name}."); // For example.
    }
}

Solution

  • Build-in DI allows registering open generic types, so if you can change the interface to be generic one, then:

    public interface IMyService<T>
    {
    }
    
    public class MyService<T> : IMyService<T>
    {
        public MyService()
        {
            Console.WriteLine($"This service was requested by {typeof(T)}."); // For example.
        }
    }
    

    With the following registration:

    services.AddTransient(typeof(IMyService<T><>), typeof(MyService<T><>)); 
    

    And then you can resolve closed type in the controller:

    public class HomeController
    {
        private readonly IMyService<HomeController> MyService;
    
        public HomeController(IMyService<HomeController> myService) 
        {
             MyService = myService;
        }
    }
    

    Basically the same as with ILogger<T> interface.