简体   繁体   中英

How to configure Dependency Injection in my own class

I wish to use settings from appsettings.json in my own class.

I have this working well in a controller and in razor. I tried to use the same code as in a controller in my own class:

public class Email
{
    private readonly IConfiguration _config;

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

but when I try to call this

Email sendEmail = new Email();

it requires that I provide config as a parameter. Shouldn't the DI system provide (inject) this? In ConfigureServices I have this:

services.AddSingleton(Configuration);

Do I need to register Email class somewhere too? Do I need to call it some different way?

When you use the following code:

Email sendEmail = new Email();

The DI system isn't involved at all - You've taken things into your own hands. Instead, you should add Email to the DI system and then have it injected. eg:

services.AddSingleton<Email>(); // You might prefer AddScoped, here, for example.

Then, as an example, if you're accessing Email in a controller, you can have it injected too:

public class SomeController : Controller
{
    private readonly Email _email;

    public SomeController(Email email)
    {
        _email = email;
    }

    public IActionResult SomeAction()
    {
         // Use _email here.
         ...
    }
}

Essentially, this just means you need to use DI all the way. If you want to provide more details about where you're currently creating your Email class, I can tailor the examples more to that.


It's a bit of an side, but you can also inject dependencies using the [FromServices] attribute inside of an action. Using this means you can skip the constructor and private field approach. eg:

public class SomeController : Controller
{
    public IActionResult SomeAction([FromServices] Email email)
    {
         // Use email here.
         ...
    }
}

As you mentioned, you defined a constructor which requires the parameter.

Please check out the concept of Class Constructors .

Injection is design pattern, when we use class and interfaces to implement it, it should still follow the basic Class methodology and concept. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM