'How do I instantiate class with dependency injection in .net core 5 or 6?
In a .net core 5 or 6 api, if I have a dependency:
services.AddScoped<IMyDependency>((svc) =>
{
return new MyDependency(appSettings.ConnectionStrings.MyDB);
});
and I have a class that uses the dependency:
public class MyClass
{
public MyClass(IMyDependency dependency)
{
...
}
}
How do I instantiate the class so that the dependency is injected into the constructor? In a controller, this is done for me when the controller is instantiated. How do I do it for my own classes?
I can use services.GetServices explicitly, but I think that is frowned upon.
Solution 1:[1]
I can use services.GetServices explicitly, but I think that is frowned upon.
Yes, this is the documented way to do it:
Services and their dependencies within an ASP.NET Core request are exposed through
HttpContext.RequestServices.
SourceHttpContext.RequestServices is of type IServiceProvider which offers the GetService method.
But it is also adviced not to do it:
Avoid using the service locator pattern. For example, don't invoke GetService to obtain a service instance when you can use DI instead
Solution 2:[2]
This won't be done by default. If you are trying to use something that is injected into the request pipeline, you would have to pass that injected value in the controller and pass it on to the constructor.
public class HomeController : Controller
{
private IMyDependency _dependency;
public HomeController(IMyDependency dependency)
{
_dependency = dependency;
}
[Route("")]
public IActionResult Index()
{
MyClass myclass = new MyClass(_dependency);
....
return View(myclass.stuff);
}
Solution 3:[3]
Add the class and its dependencies to the service collection, then inject it into your methods or use the IServiceProvider GetRequiredService
eg.
public class MyClass
{
public MyClass(IMyDependency dependency)
{
...
}
}
...
startup.cs
services.AddScoped<IMyDependency, MyDependency>();
services.AddScoped<MyClass>()
...
[Route("home")]
public IActionResult Index([FromServices]MyClass myClass)
{
var result = myClass.DoStuff();
....
return View(result);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cremor |
| Solution 2 | Ben Matthews |
| Solution 3 | Lee |
