.NET Core 2 - Create instance of controller class which has a repository

前端 未结 2 814
时光取名叫无心
时光取名叫无心 2021-01-18 21:19

I have the following controller Class;

public class MyController: Controller
{
    private IValueService _service;

    public MyController(IValueService se         


        
2条回答
  •  梦谈多话
    2021-01-18 22:01

    In Startup file add :

     services.AddMvc().AddControllersAsServices();  
    

    it will registers all controllers in your application with the DI container.

    Then :

       var serviceProvider = HttpContext.RequestServices;
         var controller =(MyController)serviceProvider.GetRequiredService();
         controller.Method();
    

提交回复
热议问题