Call an api as part of startup of an application?

Viewed 3960

I am currently in a situation where I need to call a controller as part of the startup of an application? The controller is being hosted by the application itself.. Is that somehow possible? It just needs to be triggered every time the application starts.

3 Answers

You could inject IHostApplicationLifetime on Startup.Configure() method , then write the callback for ApplicationStarted that would be triggered when the application host has fully started, and call your controller action within callback method.

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
        services.AddHttpClient();
        //register other services   
}

private async Task<Action> OnApplicationStartedAsync(IHttpClientFactory httpClientFactory)
{
        var client = httpClientFactory.CreateClient();

        var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44326/api/values");

        var response = await client.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            //deal with the response
            var result = await response.Content.ReadAsStringAsync();
        }

        return null;
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
{

        IHttpClientFactory _clientFactory = app.ApplicationServices.GetService(typeof(IHttpClientFactory)) as IHttpClientFactory;

        lifetime.ApplicationStarted.Register(OnApplicationStartedAsync(_clientFactory).Wait);

       //other middlewares
} 

I ended implementing an interface and implement the required functionality within this interface.

IControllerService.cs

public interface IControllerService
{
    void InsertIntoDB(string name);
}

Controller.cs

public InsertIntoDB(string name)
{
   ....
}

so I in my Startup.Configure could call

startup.cs

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SchemaContext schemaContext, IControllerService controllerService)
{

    ....
    controllerService.InsertIntoDB("InitData")
}

My API endpoint uses the same interface to call out

In your Startup, you could call:

public void ConfigureServices(IServiceCollection services)
{
    ...
    ...
    services.AddTransient<Interfaces.IService, Service.ServiceImplementator>();
    ...
    ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    ...
    Task.Run(() => {
                    app.ApplicationServices.GetRequiredService<Interfaces.IService>().DoWorkOnStartup();
                });
    ...
    ...
}

Don't call a controller action, I think your controller should be invoking a service to do the work.

Related