M
M
Michael2018-06-23 15:29:01
ASP.NET
Michael, 2018-06-23 15:29:01

Why are service properties not initialized when added via AddTransient in ASP.NET Core?

Hello. There is an application on ASP.NET Core 2.0. There is an EmailService class with the following content:

public class EmailService : IEmailService
{
        public string _emailAddress;
        public string _emailPassword;
        public string _name;

        public async Task SendEmail(string toAddress, string subject, string text)
        {
            //некий код
        }
}

I'm trying to add it as a service in the ConfigureServices method like so:
services.AddTransient<IEmailService, EmailService>();
services.Configure<EmailService>(options =>
{
    options._emailAddress = "email";
    options._emailPassword = "password";
    options._name = "name";
});

The project runs and compiles successfully, but the corresponding fields of the EmailService class remain null. What could be the problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
basrach, 2018-06-26
@mak_ufo

Because the built-in DI container ASP. Net Core does not support property and field injection.
And with the services.Configure method, you actually register options, which you can then get like this: IOptions
I.e. you need to do like this:

services.AddTransient<IEmailService, EmailService>();
services.Configure<EmailServiceOptions>(options =>
{
    options._emailAddress = "email";
    options._emailPassword = "password";
    options._name = "name";
});

class EmailService
{
  public EmailService(IOptions<EmailServiceOptions> optionsAccessor)
  {
    _emailAddress = optionsAcessor.Value.EmailAddress;
    ....
  }
}

R
Roman, 2018-06-24
@yarosroman

Use properties, not fields. Yes, and _ is used in naming private fields.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question