如何使用依赖项注入在剃须刀页面中检索服务 [英] How to retrieve a service in razor pages with dependency injection
本文介绍了如何使用依赖项注入在剃须刀页面中检索服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在ASP.NET Core 2应用程序中,我设置了一些服务:
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>();
}
在program.cs
中,我可以检索自己的服务:
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();
}
现在,我正试图了解在没有宿主变量的情况下如何执行相同的操作,就像在任何其他C#类中一样,甚至在cshtml页面中也是如此:
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();
}
推荐答案
asp.net核心剃须刀页面中也可以进行依赖注入.
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
}
}
在页面:)中也可以进行依赖项注入.只需使用inject
指令即可.
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
这篇关于如何使用依赖项注入在剃须刀页面中检索服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文