如何使用依赖项注入在剃须刀页面中检索服务

Mar*_*ark 2 c# asp.net-core-2.0 razor-pages

在ASP.NET Core 2应用程序中,我设置了一些服务:

 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>();
 }
Run Code Online (Sandbox Code Playgroud)

program.cs我可以检索自己的服务中:

var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    var ip = services.GetRequiredService<Importer>();
    Task task = ip.ImportListAsync();
}
Run Code Online (Sandbox Code Playgroud)

现在,我试图了解在没有宿主变量的情况下(例如在其他C#类中,甚至在cshtml页面中)如何执行相同操作:

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();
}
Run Code Online (Sandbox Code Playgroud)

Shy*_*yju 5

在asp.net核心剃刀页面中也可以进行依赖注入。

您可以在页面模型类中进行构造函数注入。

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
    }
}
Run Code Online (Sandbox Code Playgroud)

页面:)中也可以进行依赖注入。只需使用inject指令即可。

@model YourNameSpace.LoginModel 
@inject IFileSystem FileSystem;
<h1>My page</h1>
// Use FileSystem now
Run Code Online (Sandbox Code Playgroud)