In ASP.NET Core 2 application I set up some services:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyContext")));
services.AddHangfire(options => options.UseSqlServerStorage(Configuration.GetConnectionString("MyContext")));
services.AddOptions();
services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));
services.AddMvc().AddDataAnnotationsLocalization();
services.AddScoped<IMyContext, MyContext>();
services.AddTransient<IFileSystem, FileWrapper>();
services.AddTransient<Importer, Importer>();
}
In program.cs
I'm able to retrieve my own Service:
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var ip = services.GetRequiredService<Importer>();
Task task = ip.ImportListAsync();
}
Now I'm trying to understand how to do the same when I don't have the host variable, like in any other C# class or even if a cshtml page:
public async Task<IActionResult> OnPostRefresh()
{
if (!ModelState.IsValid)
{
return Page();
}
// host is not defined: how to retrieve it?
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var ip = services.GetRequiredService<Importer>();
Task task = ip.ImportListAsync();
}
return RedirectToPage();
}