How to retrieve a service in razor pages with dependency injection

孤街醉人 提交于 2019-12-12 19:17:17

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/47463206/how-to-retrieve-a-service-in-razor-pages-with-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!