question

JerryLipan-2008 avatar image
0 Votes"
JerryLipan-2008 asked cooldadtx answered

Regarding Class and Constructor

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
001.png (25.7 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

cooldadtx avatar image
0 Votes"
cooldadtx answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.