How to retrieve a service in razor pages with dependency injection

后端 未结 1 1642
刺人心
刺人心 2021-01-21 18:20

In ASP.NET Core 2 application I set up some services:

 public void ConfigureServices(IServiceCollection services)
 {
    services.AddDbContext(o         


        
1条回答
  •  面向向阳花
    2021-01-21 18:55

    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 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;
    

    My page

    // Use FileSystem now

    0 讨论(0)
提交回复
热议问题