在 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>();
}
在
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();
}
现在我试图了解当我没有主机变量时如何执行相同的操作,就像在任何其他 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();
}
在 asp.net core razor 页面中也可以进行依赖注入。
您可以在页面模型类中进行构造函数注入。
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
指令即可。
@model YourNameSpace.LoginModel
@inject IFileSystem FileSystem;
<h1>My page</h1>
// Use FileSystem now
在 .NET 6 中,过程已被简化。
在 .NET 6 Core Web 应用程序 (Razor Pages) 中,您需要将服务接口添加到 Program.cs 中的 Web 应用程序生成器的实现映射,如下所示:
builder.Services.AddScoped<IMyDependency, MyDependency>();
更多信息可以在 ASP 中的依赖注入中找到。 NET核心
完成后,您可以如上所述在页面模型类中使用依赖项注入。