.Net Bootstrap Console App with IOC using DI

Spread the love

We can use the HostApplicationBuilder Class (Microsoft.Extensions.Hosting) | Microsoft Learn to create a host with default settings. It’s very quick and easy to set a console app with IOC principle using dependency injection pattern. Your appsettings data will be there in the ‘Configuration’ prop of the host builder.

Example code

var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "DEV";

var hostBuilder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings()
{
    EnvironmentName = environmentName
});

hostBuilder.Register(); // register the service in the container

var host = hostBuilder.Build(); // build the host

StartMyFunc(host.Services); // execute something

await host.RunAsync(); // Wait the current thread.

StartMyFunc will look something like below:

static void StartMyFunc(IServiceProvider hostServiceProvider)
{
    // create a scope, so that we can use the scoped services
    using IServiceScope serviceScope = hostServiceProvider.CreateScope();
    
    IServiceProvider scopedServiceProvider = serviceScope.ServiceProvider;

    // get the IMyService implementation registered in 'Register' function
    var myService = scopedServiceProvider.GetRequiredService<IMyService>();
 
    // we can't make it async, if you have multiple things to execute simultaneously 
    // then use a List to store the tasks and wait for them complete using Task.Wait()
    myService.ExecuteSomething().GetAwaiter().GetResult();
}

Cheers and Peace out!!!

Leave a Reply

Your email address will not be published. Required fields are marked *