Sagar Chaudhary
Sagar Chaudhary

Reputation: 1403

Migration asp.net web api to asp.net core

My asp.net static constructor which was getting called when sending mail

static EmailHelper()
        {
            //load configuration from config file

            int intSmtpPort = 0;
            int.TryParse(WebConfigurationManager.AppSettings["smtpport"], out intSmtpPort);
            host = WebConfigurationManager.AppSettings["smtpclient"];
            port = intSmtpPort;
            user = WebConfigurationManager.AppSettings["username"];
            password = WebConfigurationManager.AppSettings["password"];
            fromEmail = WebConfigurationManager.AppSettings["frommail"];

        }

My asp.net core static constructor class which throws error as it should be parameterless but i need to use the configuration

 static EmailHelper(IOptions<SmtpConfig> smtpConfig)
        {
            int intSmtpPort = 0;
            int.TryParse(SmtpConfig.smtpport, out intSmtpPort);
            host = SmtpConfig.smtpclient;
            port = intSmtpPort;
            user = SmtpConfig.username;
            password = SmtpConfig.password;
            fromEmail = SmtpConfig.frommail;

        }

If i use a public constructor its not getting called. What should i do? Is there another way to inject configuration settings in my class without using dependency injection?

Upvotes: 0

Views: 273

Answers (1)

Juergen Gutsch
Juergen Gutsch

Reputation: 1764

A static constructor cannot be used for dependency injection.

Why don't you make a non-static constructor and register the EmailHelper as a service in the dependency injection?

This way you can inject and use the EmailHelper anywhere you need it.

Upvotes: 1

Related Questions