'.Net Core Dependency Injection inject out of constructor
I need to inject out of constructor, everything I declared in Setup.
Ho can I do it ? How can I inject services out of constructor ? Something like Injector service in Angular 2.
INJECT SERVICES WITHOUT CONSTRUCTOR IN CONTROLLERS
something like this
public class ControllerBase : Controller
{
protected IRepository<Test> _test;
protected IRepository<Test1> _test1;
protected IRepository<Test2> _test2;
public ControllerBase(INJECTOR injector)
{
_test = injector.inject(IRepository<Test>);
_test1 = injector.inject(IRepository<Test1>);
_test2 = injector.inject(IRepository<Test2>);
}
}
public class SomeController : ControllerBase
{
public SomeController(INJECTOR injector)
: base(injector)
{
}
}
THANKS FOR ANSWER @Rick van den Bosch
FOR THOSE WHO STILL CAN'T GET WHAT I WANTED:
public class ControllerBase : Controller
{
protected IRepository<Test> _test;
protected IRepository<Test1> _test1;
protected IRepository<Test2> _test2;
public ControllerBase(IServiceProvider injector)
{
_test = injector.GetService<IRepository<Test>>();
_test1 = injector.GetService<IRepository<Test1>>();
_test2 = injector.GetService<IRepository<Test2>>();
}
}
public class SomeController : ControllerBase
{
public SomeController(IServiceProvider injector)
: base(injector)
{
//HERE I HAVE ALL 3 REPO NOW WITHOUT EXTRA LINES
}
}
public class SomeController1 : ControllerBase
{
public SomeController1(IServiceProvider injector)
: base(injector)
{
//HERE I HAVE ALL 3 REPO NOW WITHOUT EXTRA LINES
}
}
Solution 1:[1]
You can inject the service as a parameter to the action method. This is done by marking the parameter with the attribute [FromServices]
.
This looks something like this:
public IActionResult About([FromServices] IDateProvider dateProvider)
{
ViewData["Message"] = $"Current date is {dateProvider.CurrentDate}";
return View();
}
If you're looking for default services in a BaseController: you could go about that several ways:
1. Still use a constructor
This would look something like this:
public class HomeController : BaseController
{
public HomeController(IDateProvider dateProvider) : base(dateProvider)
{
}
}
and
public class BaseController
{
protected IDateProvider _dateProvider;
protected BaseController(IDateProvider dateProvider)
{
_dateProvider = dateProvider;
}
}
This way the IDateProvider is available to both the BaseController and all inheriting Controllers.
2. Resolve services manually
This way you resolve the service manually. This could be in the BaseController, and only when you need them (lazy). For more info, see this post.
For simplicity and readability I would probably choose the constructor one.
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 | rickvdbosch |