I'm struggling with this concept of dependency injection. Here is one of the articles I am reading:
https://www.dotnettricks.com/learn/dependencyinjection/implementation-asp-net-core-mvc
Here is the first part of my class:
private readonly IConfiguration _configuration;
public Mailgun(IConfiguration configuration)
{
_configuration = configuration;
}
IConfiguration contains the connection information needed to connect to the MailGun API wrapper.
And here is where I tried passing the Configuration in Program.cs
(mostly as it comes out of the box with a new ASP.NET Core 7 MVC project:
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddTransient<IConfiguration, Mailgun>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
This line is where I am attempting to pass the dependency above:
builder.Services.AddTransient<IConfiguration, Mailgun>();
But the error is
Error CS0311 The type 'Mailgun' cannot be used as type parameter 'TImplementation' in the generic type or method 'ServiceCollectionServiceExtensions.AddTransient<TService, TImplementation>(IServiceCollection)'. There is no implicit reference conversion from 'Mailgun' to 'Microsoft.Extensions.Configuration.IConfiguration'.
I understand the error but do not understand how to inject IConfiguration
into my class.
Could someone please show me how this is meant to be accomplished?