c# - 如何在我自己的类中配置依赖注入
问题描述
我希望在我自己的班级中使用 appsettings.json 中的设置。
我在控制器和剃须刀中都能很好地工作。我尝试在我自己的类中使用与控制器中相同的代码:
public class Email
{
private readonly IConfiguration _config;
public Email(IConfiguration config)
{
_config = config;
}
但是当我尝试调用它时
Email sendEmail = new Email();
它要求我提供配置作为参数。DI系统不应该提供(注入)这个吗?在 ConfigureServices 我有这个:
services.AddSingleton(Configuration);
我是否也需要在某处注册电子邮件课程?我需要用不同的方式称呼它吗?
解决方案
当您使用以下代码时:
Email sendEmail = new Email();
DI系统根本不参与——你已经把事情掌握在自己手中。相反,您应该添加Email
到 DI 系统,然后将其注入。例如:
services.AddSingleton<Email>(); // You might prefer AddScoped, here, for example.
然后,作为一个例子,如果你Email
在一个控制器中访问,你也可以注入它:
public class SomeController : Controller
{
private readonly Email _email;
public SomeController(Email email)
{
_email = email;
}
public IActionResult SomeAction()
{
// Use _email here.
...
}
}
本质上,这只是意味着您需要一直使用 DI。如果您想提供更多关于您当前在何处Email
创建课程的详细信息,我可以针对此定制更多示例。
这有点偏,但您也可以使用[FromServices]
动作内部的属性注入依赖项。使用这意味着您可以跳过构造函数和私有字段方法。例如:
public class SomeController : Controller
{
public IActionResult SomeAction([FromServices] Email email)
{
// Use email here.
...
}
}
推荐阅读
- asp.net - 无法修复 Global.asax 错误:“无法加载类型 'ApplicationName.Global”
- javascript - 确保桌面上有后退按钮(Windows 10)PWA
- c# - Google Contacts API - PostalAddress Country not working set value
- linux - 从 gitlab docker runner 启动 Sonar Scanner
- android - 如何以编程方式将 autoSizeTextType 转换为 unifrom?
- bash - 如何替换 cloudbuild.yaml 中的替换字符串
- python - 如何使用 scikitlearn 保存一个热编码模型并预测新的未编码数据?
- python - 使用 pyspark 从数据框创建 json 结构
- sharepoint - 基于下拉列表计算的列
- console - console.log 是异步的吗?