How to retrieve a service in razor pages with dependency injection

Viewed 9497

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();
}
2 Answers

Dependency injection is possible in asp.net core razor pages as well.

You can do constructor injection in your page model class.

public class LoginModel : PageModel
{
    private IFileSystem fileSystem;
    public LoginModel(IFileSystem fileSystem)
    {
        this.fileSystem = fileSystem;
    }

    [BindProperty]
    public string EmailAddress { get; set; }

    public async Task<IActionResult> OnPostRefresh()
    {
       // now you can use this.fileSystem
       //to do : return something
    }
}

Dependency injection is also possible in the pages :). Simply use the inject directive.

@model YourNameSpace.LoginModel 
@inject IFileSystem FileSystem;
<h1>My page</h1>
// Use FileSystem now

In .Net 6 the procedure has been simplified.

In a .NET 6 Core Web App (Razor Pages) you need to add the service interface to implementation mapping to the Web Application Builder in Program.cs as follows: builder.Services.AddScoped<IMyDependency, MyDependency>(); More information can be found at Dependency injection in ASP.NET Core

When you've done that you can use dependency injection in your page model class as described above.

Related