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

前端 未结 2 790
时光取名叫无心
时光取名叫无心 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:03

    Well, on startup I would like to run a method in a class that uses a repository. This method first opens a SocketIO connection and then it should use the repository to save new incoming data to the database.

    Then that logic shouldn’t be inside a controller but in some service type instead which you register with the dependency injection container. Controllers are to respond to requests at certain routes, but your thing sounds like it’s a general initialization step in your application that runs outside of a request. So there should be no controller involved.

    Instead, you want to make some service first:

    public class MyInitializationService
    {
        private readonly IValueService _valueService;
    
        public MyInitializationService(IValueService valueService)
        {
            _valueService = valueService;
        }
    
        public void Initialize()
        {
            var values = _valueService.GetAll();
            // do something
        }
    }
    

    You then register that class in the ConfigureServices method of your Startup class:

    services.AddTransient();
    

    And then, you can inject that type into the Configure method and call its Initialize method:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, MyInitializationService initializationService)
    {
        initializationService.Initialize();
    
        // …
        app.UseStaticFiles();
        app.UseMvc();
    }
    

    There are various ways of running something at the beginning when an application starts. Calling it inside Configure is just one way, which may or may not be appropriate depending on how early you want your code to run (since Configure runs very early). Another good way would be to register a callback to the ApplicationStarted event of the application lifetime. I have an answer over here which goes into more details on that.

提交回复
热议问题