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.