Regarding Class and Constructor

Jerry Lipan 916 Reputation points
2021-09-22T13:54:55.01+00:00

Hi there,

I've Class as following,

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using System.Net.Mail;  
using Microsoft.Extensions.Configuration;  
  
namespace HelpDesk.Email  
{  
    public class EmailHelper  
    {  
        IConfiguration _iconfigration;  
  
        public EmailHelper(IConfiguration iconfiguration)  
        {             
            _iconfigration = iconfiguration;              
        }  
  
        public bool SendEmail(string userEmail, string confirmationLink)  
        {  
            MailMessage mailMessage = new MailMessage();  
            mailMessage.From = new MailAddress(_iconfigration["mailUsername"].ToString());  
            mailMessage.To.Add(new MailAddress(userEmail));  
  
            mailMessage.Subject = "Confirm your email";  
            mailMessage.IsBodyHtml = true;  
            mailMessage.Body = confirmationLink;  
  
            SmtpClient client = new SmtpClient();  
            client.Credentials = new System.Net.NetworkCredential(_iconfigration["mailUsername"].ToString(),   
                _iconfigration["mailPassword"].ToString());  
            client.Host = _iconfigration["mailHost"].ToString();  
            client.Port = Convert.ToInt32(_iconfigration["mailPort"].ToString());  
  
            try  
            {  
                client.Send(mailMessage);  
                return true;  
            }  
            catch (Exception ex)  
            {  
                // log exception  
            }  
            return false;  
        }  
  
        public bool SendEmailPasswordReset(string userEmail, string link)  
        {  
            MailMessage mailMessage = new MailMessage();  
            mailMessage.From = new MailAddress(_iconfigration["mailUsername"].ToString());  
            mailMessage.To.Add(new MailAddress(userEmail));  
  
            mailMessage.Subject = "Password Reset";  
            mailMessage.IsBodyHtml = true;  
            mailMessage.Body = link;  
  
            SmtpClient client = new SmtpClient();  
            client.Credentials = new System.Net.NetworkCredential(_iconfigration["mailUsername"].ToString(),  
                _iconfigration["mailPassword"].ToString());  
            client.Host = _iconfigration["mailHost"].ToString();  
            client.Port = Convert.ToInt32(_iconfigration["mailPort"].ToString());  
  
            try  
            {  
                client.Send(mailMessage);  
                return true;  
            }  
            catch (Exception ex)  
            {  
                // log exception  
            }  
            return false;  
        }  
  
        public bool SendEmailTwoFactorCode(string userEmail, string code)  
        {  
            MailMessage mailMessage = new MailMessage();  
            mailMessage.From = new MailAddress(_iconfigration["mailUsername"].ToString());  
            mailMessage.To.Add(new MailAddress(userEmail));  
  
            mailMessage.Subject = "Two Factor Code";  
            mailMessage.IsBodyHtml = true;  
            mailMessage.Body = code;  
  
            SmtpClient client = new SmtpClient();  
            client.Credentials = new System.Net.NetworkCredential(_iconfigration["mailUsername"].ToString(),  
                _iconfigration["mailPassword"].ToString());  
            client.Host = _iconfigration["mailHost"].ToString();  
            client.Port = Convert.ToInt32(_iconfigration["mailPort"].ToString());  
  
            try  
            {  
                client.Send(mailMessage);  
                return true;  
            }  
            catch (Exception ex)  
            {  
                // log exception  
            }  
            return false;  
        }  
  
    }  
}  
  

  

134361-001.png

EmailHelper emailHelper = new EmailHelper();  

There is no argument given

How to set the argument ?

Small BASIC
Small BASIC
A programming language created by Microsoft that serves a stepping stone for beginners from block-based coding languages to more complex text-based languages.
277 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 48,281 Reputation points
    2021-09-22T14:14:13.383+00:00

    The constructor requires an IConfiguration object to be created.

       public EmailHelper(IConfiguration iconfiguration)  
    

    This looks like an ASP.NET Core/5 application to me. Therefore IConfiguration is provided by the framework. In order to get that instance you will be using the dependency injection container provided by the framework. The purpose of the DI is to automatically hook up your dependencies for you. That means your code won't be littered with new statements and figuring out what parameters to pass to constructors. Instead you simply ask for the dependency you need and the DI container handles giving you back a fully constructed one. This is generally done via the constructor.

    Imagine you are using this EmailHelper class in a controller, then you'd simply add it as a parameter to the controller's constructor and DI would handle the rest.

       public class MyController  
       {  
          //Argument provided by DI container  
          public MyController ( EmailHelper email )  
          {  
             _email = email;  
          }  
         
          public void DoSomething ()  
          {  
             _email.SendEmail("", "");  
          }  
         
          private readonly EmailHelper _email;  
       }  
    

    For this to work you must configure the types you want to support and this happens at startup. Within your app it is already configuring everything for you so you would simply add a registration for your type.

       //Pre-existing ConfigureServices contained in startup.cs  
       services.AddTransient<EmailHelper>();  //Now DI container can return EmailHelper instances on deman  
    

    Since IConfiguration is provided by the framework it should already be registered so you are good to go. If you aren't using ASP.NET Core but just NET Core then you can still use DI but you have to do some registration yourself as discussed in the link given earlier.

    A final note, it is not generally recommended that you rely on IConfiguration at all. This is for the configuration subsystem and not direct consumption. The preferred approach is to create a custom Options class to hold just the settings you need. Then register the options in the DI Container. This gives you the flexibility of being able to configure the type via appsettings or similar or just passing the configured options directly. During startup you would register the options using the IConfiguration instance that is provided during startup.

    Refer to the IOptions documentation for more information.

    0 comments No comments

0 additional answers

Sort by: Most helpful