In our ASP.NET core application we are using DI so either of these work just find:
public class MyController : ControllerBase
{
private readonly IMyService _myService
public MyController(IServiceProvider serviceProvider)
{
_myService = serviceProvider.GetService<IMyService>();
}
}
public class MyController : ControllerBase
{
private readonly IMyService _myService
public MyController(IMyService myService)
{
_myService = myService;
}
}
I have a service with constructor parameters that I would like to inject but I'm not seeing a way to do that. For example:
public class MyOtherService
{
public MyOtherService(string param1, MyType param2)
{
// do constructor stuff
}
}
I'd like to do something like this:
public MyController(IServiceProvider serviceProvider)
{
_myService = serviceProvider.GetService<IMyOtherService>("someText", new MyType());
}
public MyOtherController(IServiceProvider serviceProvider)
{
_myService = serviceProvider.GetService<IMyOtherService>("differentText", new MyOtherType());
}
However serviceProvider.GetService does not take constructor parameters. Is there a way to inject services with constructor parameters?
This question .NET Core DI, ways of passing parameters to constructor is asking about passing predefined parameters when the service is setup. services.AddSingleton, services.AddSingleton, services.AddScoped, etc. In that case use you can use a factory method to get different versions of the service with different predefined parameters pass in.
What I'm asking about is passing parameters at runtime when the service is created using serviceProvider.GetService, etc. From what I understand other DI service providers have this ability.