Answer the question
In order to leave comments, you need to log in
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)
{
//некий код
}
}
services.AddTransient<IEmailService, EmailService>();
services.Configure<EmailService>(options =>
{
options._emailAddress = "email";
options._emailPassword = "password";
options._name = "name";
});
Answer the question
In order to leave comments, you need to log in
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;
....
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question