且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-20 18:33:11

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