简体   繁体   中英

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?

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.

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