首页 > 解决方案 > 如何在我自己的类中配置依赖注入

问题描述

我希望在我自己的班级中使用 appsettings.json 中的设置。

我在控制器和剃须刀中都能很好地工作。我尝试在我自己的类中使用与控制器中相同的代码:

public class Email
{
    private readonly IConfiguration _config;

    public Email(IConfiguration config)
    {
        _config = config;
    }

但是当我尝试调用它时

Email sendEmail = new Email();

它要求我提供配置作为参数。DI系统不应该提供(注入)这个吗?在 ConfigureServices 我有这个:

services.AddSingleton(Configuration);

我是否也需要在某处注册电子邮件课程?我需要用不同的方式称呼它吗?

标签: c#asp.net-core.net-coreasp.net-core-mvc.net-core-2.1

解决方案


当您使用以下代码时:

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.
         ...
    }
}

推荐阅读