SoFunction
Updated on 2025-03-07

Quickly learn how to build a host using Generic-Host in .NETCORE

Generic Host in .NETCORE

This article summarizes the study and use of .net core generic-host at work.

Preface

In the created ASPNETCORE project we canMain()See, we passIWebHostBuildCreated aIWebHost, and Microsoft provides(args)Let's help us create more easilyWebHost

Often our needs do not require creating web projects, such as background tasks, so how do we create console projects like using AspNetCore?

How to create a host in a console program

passdotnet new console Create a console project

Add the following package via Nuget

First, let's take a lookIHostBuilderMethods in the interface

public interface IHostBuilder
{
 IHost Build();

 IHostBuilder ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate);

 IHostBuilder ConfigureContainer<TContainerBuilder>(Action<HostBuilderContext, TContainerBuilder> configureDelegate);

 IHostBuilder ConfigureHostConfiguration(Action<IConfigurationBuilder> configureDelegate);

 IHostBuilder ConfigureServices(Action<HostBuilderContext, IServiceCollection> configureDelegate);
 
 IHostBuilder UseServiceProviderFactory<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory);
}

ConfigureAppConfiguration()You can configure some configurations of your application, such as environment variables, etc.

ConfigureContainer() & UseServiceProviderFactory() You can configure components that replace the default dependency injection, such as replacing it with Autofac

ConfigureHostConfiguration() Can be configuredIConfiguration

ConfigureServices() Can inject services

Next, through the following code, we can build a simple host.

static void Main(string[] args)
{
 CreateDefaultHost(args).Build().Run();
}static IHostBuilder CreateDefaultHost(string[] args) => new HostBuilder()
 .ConfigureHostConfiguration(builder =>
 {  //todo
 })
 .ConfigureAppConfiguration((ctx, builder) =>
 {
  builder
   .SetBasePath()
   .AddJsonFile("", true, true)
   .AddJsonFile($"appsettings.{}.json", true, true)
   .AddEnvironmentVariables()
   ;
 })
 .ConfigureServices((ctx, services) =>
 {
  ();
  <CustomHostService>();
 })
 .UseConsoleLifetime()
 ;
public class CustomHostService: IHostedService{ private ILogger _logger; private Task _executingTask; public Task StartAsync(...) {
  _logger.LogInformation($"{nameof(CustomHostService):}start");

  _executingTask = ExecuteAsync(...);  if(_executingTask.IsCompleted){   return _executingTask;
  }  return ;
 } public Task StopAsync(CancellationToken cancellationToken) {  return (_executingTask, (, cancellationToken));
 } public Task ExecuteAsync(...) {
  _logger.LogInformation($"{nameof(CustomHostService):executing}")  return (5000);
 }

}

As mentioned above, we customized CustomHostService Need to be implementedIHostedServiceThe interface, of course, can be directly inheritedBackgoundServicekind.

Implemented IHostedService After the interface, we pass <>() Inject, or through<IHostedService,THostedService>() Enter the injection.

Starting the above project, we found that our program defaultsHosting EnvironmentAlwaysProduction, so how to modify it ??

Configure environment variables

In the AspNetCore project, we can set environment variables by settingASPNETCORE_ENVIRONMENTThe value of the host environment variable is specified. However, this configuration is not available in Generic Host for the time being.

If viewIHostBuilderWe will find the following methods for extension:

new HostBuilder()
 .UseContentRoot(...)
 .UseEnvironment(...) ...

After viewing the source code, we can useConfigureHostConfiguration()Method Configure these configurations into the host.

Now let's assume we haveDOTNETCORE_ENVIRONMENTTo specify the GenericHost environment.

new HostBuilder().ConfigureHostConfiguration(builder =>
 {
  (new Dictionary<string, string>
  {
   [] = ("DOTNETCORE_ENVIRONMENT"),
  })  // Nuget:
  //.AddCommandLine(args) 
  ;
 }) 
 //...

Now let's open the command line test. After setting the environment variables, we passdotnet run Start the program. View the output, Host Environment becomesStage

# Set the environment variable $env:DOTNETCORE_ENVIRONMENT='Stage'# View the environment variable $env:DOTNETCORE_ENVIRONMENT
Of course, we can also set the startup environment variable equivalent values ​​through the commandline parameter.

Install-Package 

existConfigureHostConfiguration()Used in.AddCommandLine(args)to specify parameters.

Now we can passdotnet run --environment=DevelopmentWe have come to specify the dev environment, and now we find that we have finally loaded successfullyConfiguration information in.

Use Autofac to replace the default DI
A brief understanding of Autofac

A third-party dependency injection container, relativeIt is easier to use.

Integrate into Host

Install the following two packages via Nuget

Install-Package Autofac

Install-Package 

We can useUseServiceProviderFactory()and() Replace the default DI with Autofac;

useConfigureContainer<ContainerBuilder>()Autofac can be used to inject services;

//The non-critical code is omitted. static IHostBuilder CreateDefaultHost(string[] args) => new HostBuilder()//... omitted .ConfigureServices((ctx, services) =&gt;
 {
  (x=&gt;{();});

  ();
 })
 .ConfigureContainer&lt;ContainerBuilder&gt;(builder =&gt; 
 {
  &lt;CustomHostService&gt;()
  .As&lt;IHostedService&gt;()
  .InstancePerDependency();
 })   
 .UseServiceProviderFactory&lt;ContainerBuilder&gt;(new AutofacServiceProviderFactory())//...slightly

Summarize

Personally, I think there are several pain points that GenericHost solves. Compared with the pipeline mechanism in AspNetCore, if the console program does not rely on GenericHost to manage Di, it would like to do a lot of things.Package integration can be very difficult. Through IHostedService, service hosting can be conveniently managed.

The above is the detailed content of the method of using Generic-Host. For more information about using Generic-Host, please follow my other related articles!