我需要从构造函数中注入我在 Setup 中声明的所有内容.
I need to inject out of constructor, everything I declared in Setup.
我能做到吗?如何从构造函数中注入服务?类似于 Angular 2 中的 Injector 服务.
Ho can I do it ? How can I inject services out of constructor ? Something like Injector service in Angular 2.
在控制器中没有构造函数的情况下注入服务
类似的东西
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)
{
}
}
感谢@Rick van den Bosch 的回答
对于那些仍然无法得到我想要的东西的人:
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
}
}
您可以将服务作为参数注入到操作方法中.这是通过使用属性 [FromServices]
标记参数来完成的.
You can inject the service as a parameter to the action method. This is done by marking the parameter with the attribute [FromServices]
.
这看起来像这样:
public IActionResult About([FromServices] IDateProvider dateProvider)
{
ViewData["Message"] = $"Current date is {dateProvider.CurrentDate}";
return View();
}
如果您正在寻找 BaseController 中的默认服务:您可以通过以下几种方式进行:
If you're looking for default services in a BaseController: you could go about that several ways:
1.仍然使用构造函数
这看起来像这样:
1. Still use a constructor
This would look something like this:
public class HomeController : BaseController
{
public HomeController(IDateProvider dateProvider) : base(dateProvider)
{
}
}
和
public class BaseController
{
protected IDateProvider _dateProvider;
protected BaseController(IDateProvider dateProvider)
{
_dateProvider = dateProvider;
}
}
这样 IDateProvider 对 BaseController 和所有继承的 Controller 都可用.
This way the IDateProvider is available to both the BaseController and all inheriting Controllers.
<强>2.手动解析服务
这样您就可以手动解析服务.这可能在 BaseController 中,并且仅在您需要它们时(懒惰).有关详细信息,请参阅这篇文章.
为了简单和可读性,我可能会选择构造函数.
For simplicity and readability I would probably choose the constructor one.
这篇关于.Net Core Dependency Injection 从构造函数中注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!