如何在我自己的系统中配置依赖注入 class
How to configure Dependency Injection in my own class
我希望在我自己的 class 中使用来自 appsettings.json 的设置。
我在控制器和剃须刀中运行良好。我尝试在自己的 class:
中使用与控制器中相同的代码
public class Email
{
private readonly IConfiguration _config;
public Email(IConfiguration config)
{
_config = config;
}
但是当我尝试调用它时
Email sendEmail = new Email();
它要求我提供配置作为参数。 DI系统不应该提供(注入)这个吗?在 ConfigureServices 我有这个:
services.AddSingleton(Configuration);
我是否也需要在某处注册电子邮件 class?我需要用不同的方式来称呼它吗?
当您使用以下代码时:
Email sendEmail = new Email();
根本不涉及 DI 系统 - 你已经把事情掌握在自己手中。相反,您应该将 Email
添加到 DI 系统,然后注入 it。例如:
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
class 的位置的更多详细信息,我可以针对此进一步调整示例。
这有点偏向,但您也可以在操作中使用 [FromServices]
属性注入依赖项。使用这意味着您可以跳过构造函数和私有字段方法。例如:
public class SomeController : Controller
{
public IActionResult SomeAction([FromServices] Email email)
{
// Use email here.
...
}
}
如您所述,您定义了一个需要参数的构造函数。
请检查Class Constructors的概念。
注入是设计模式,当我们使用class和接口来实现它时,它仍然应该遵循基本的Class方法论和概念。
希望对你有帮助。
我希望在我自己的 class 中使用来自 appsettings.json 的设置。
我在控制器和剃须刀中运行良好。我尝试在自己的 class:
中使用与控制器中相同的代码public class Email
{
private readonly IConfiguration _config;
public Email(IConfiguration config)
{
_config = config;
}
但是当我尝试调用它时
Email sendEmail = new Email();
它要求我提供配置作为参数。 DI系统不应该提供(注入)这个吗?在 ConfigureServices 我有这个:
services.AddSingleton(Configuration);
我是否也需要在某处注册电子邮件 class?我需要用不同的方式来称呼它吗?
当您使用以下代码时:
Email sendEmail = new Email();
根本不涉及 DI 系统 - 你已经把事情掌握在自己手中。相反,您应该将 Email
添加到 DI 系统,然后注入 it。例如:
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
class 的位置的更多详细信息,我可以针对此进一步调整示例。
这有点偏向,但您也可以在操作中使用 [FromServices]
属性注入依赖项。使用这意味着您可以跳过构造函数和私有字段方法。例如:
public class SomeController : Controller
{
public IActionResult SomeAction([FromServices] Email email)
{
// Use email here.
...
}
}
如您所述,您定义了一个需要参数的构造函数。
请检查Class Constructors的概念。
注入是设计模式,当我们使用class和接口来实现它时,它仍然应该遵循基本的Class方法论和概念。 希望对你有帮助。