I'm using ASP.NET Core MVC 2.2 and I need to get the current URL of the website in the ConfigureServices method of Startup.cs.
This is because the URL is passed into the constructor of a library that I am configuring in that method.
services.AddScoped<IEmailProvider>(ep => new SendGridEmailProvider(Configuration["Email:SendGridApiKey"],
Configuration.GetValue<bool>("Email:TestMode", true),
Configuration["Email:TestModeEmailAddresses"],
Configuration["ENVIRONMENT"],
"THIS SHOULD BE THE APPLICATION URL"));
I'm pretty sure that I can't use standard dependency injection techniques within ConfigureServices as this is where all the dependency injection is actually set up!
Is there some way of getting the current URL of the request? I just need the base URL like www.site.com.
You can add the HttpContext
to the DI container:
services.AddHttpContextAccessor();
Then you can make a class to hold your EmailOptions
:
public class EmailOptions
{
public string ApiKey { get; set; }
public bool TestMode { get; set; }
public string TestModeEmail { get; set; }
public string Environment { get; set; }
public string Url { get; set; }
}
Then add a class to configure your EmailOptions
:
public class ConfigureEmailOptions : IConfigureOptions<EmailOptions>
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IConfiguration _configuration;
private readonly IHostingEnvironment _environment;
public ConfigureEmailOptions(
IHttpContextAccessor httpContextAccessor,
IConfiguration configuration,
IHostingEnvironment environment)
{
_httpContextAccessor = httpContextAccessor;
_configuration = configuration;
_environment = environment;
}
public void Configure(EmailOptions options)
{
options.ApiKey = _configuration["Email:SendGridApiKey"];
options.TestMode = _configuration.GetValue<bool>("Email:TestMode", true);
options.TestModeEmail = _configuration["Email:TestModeEmailAddresses"];
options.Environment = _environment.EnvironmentName;
options.Url = _httpContextAccessor.HttpContext.Request.Scheme + "://" + _httpContextAccessor.HttpContext.Request.Host + _httpContextAccessor.HttpContext.Request.PathBase;
}
}
Then add your EmailOptions
to the DI container:
services.AddTransient<IConfigureOptions<EmailOptions>, ConfigureEmailOptions>();
services.Configure<EmailOptions>(Configuration);
After that, you should be able to inject IOptions<EmailOptions>
into your SendGridEmailProvider
. (You could also inject IHttpContextAccessor
directly into your SendGridEmailProvider
, but that would be a tighter coupling.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With