Generic host builder

What would be the equivalent code of web host builder for generic host builder for console application in 'Microsoft.Extensions.Hosting':

var hostBuilder = WebHost.CreateDefaultBuilder(args).UseConfiguration(config).UseStartup<TStartup>(); 

2 Answers

I couldn't find exactly analog. I use the next code for that. For my background services.

 public static async Task Main(string[] args) { var host = new HostBuilder() .ConfigureHostConfiguration(configHost => configHost.AddEnvironmentVariables("ASPNETCORE_")) .ConfigureAppConfiguration((hostContext, configApp) => { configApp.SetBasePath(GetConfigDirectoryPath()); configApp.AddJsonFile("appsettings.json", optional: false); configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); }) .ConfigureServices(ConfigureServices) .UseHostedService<MyBackgroundService>() .Build(); await host.RunAsync(); } private static void ConfigureServices(HostBuilderContext hostBuilderContext, IServiceCollection services) { services.AddDbContext<AppDbContext>(options => options.UseSqlServer(hostBuilderContext.Configuration.GetConnectionString("Default"))); services.AddTransient<IDbContextProvider<AppDbContext>, DefaultDbContextProvider>(); services.AddTransient<IUnitOfWorkManager, UnitOfWorkManager>(); services.AddTransient(typeof(IUnitOfWork), typeof(EfCoreUnitOfWork)); services.AddTransient(typeof(IReadOnlyRepository<>), typeof(EfCoreReadOnlyRepositoryBase<>)); services.AddTransient(typeof(IReadOnlyRepository<,>), typeof(EfCoreReadOnlyRepositoryBase<,>)); services.AddTransient(typeof(IRepository<>), typeof(EfCoreRepositoryBase<>)); services.AddTransient(typeof(IRepository<,>), typeof(EfCoreRepositoryBase<,>)); services.AddDistributedRedisCache(options => options.Configuration = hostBuilderContext.Configuration.GetSection("Redis:Configuration").Value); //Register AutoMapper profiles var assemblies = AppDomain.CurrentDomain.GetAssemblies(); services.AddAutoMapper(assemblies); } 

Is implementing background service

 public class MyBackgroundService : BackgroundService 
 public static class Extensions { public static IHostBuilder UseHostedService<T>(this IHostBuilder hostBuilder) where T : class, IHostedService, IDisposable { return hostBuilder.ConfigureServices(services => services.AddHostedService<T>()); } } 

Would have been nice if you could elaborate what exactly you are looking for but following is from my sample console application written in .net6. wrote this to show-case dependency injection and use of NLog with Microsoft.Extensions.Logging

Skip following and Get the source from Github

Program.cs

using System.Reflection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using RedBeans.Examples.Console.DependencyInjectionLoggingExample; Console.WriteLine("Hello, World!"); await Host.CreateDefaultBuilder(args) .UseContentRoot(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)) .ConfigureServices((context, services) => { services.AddHostedService<MyApplication>() .AddTransient<AnotherClass>() .AddOptions<ConfigSection1Settings>().Bind(context.Configuration.GetSection("ConfigSection1")); }) .ConfigureLogging((context, logging) => { logging.ClearProviders(); logging.AddConfiguration(context.Configuration.GetSection("NLog")); logging.AddNLog(); }) .RunConsoleAsync(); 

MyApplication.cs

namespace RedBeans.Examples.Console.DependencyInjectionLoggingExample; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; internal class MyApplication : IHostedService { private int? _exitCode; private readonly ILogger<MyApplication> _logger; private readonly AnotherClass _another; private readonly IHostApplicationLifetime _applicationLifetime; public MyApplication(IHostApplicationLifetime applicationLifetime, AnotherClass another, ILogger<MyApplication> logger) { _applicationLifetime = applicationLifetime; _another = another; _logger = logger; } public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation($"Starting Application with arguments: {string.Join(";", Environment.GetCommandLineArgs())}"); _applicationLifetime.ApplicationStarted.Register(() => { Task.Run(async () => { try { _logger.LogInformation("My Application Business logic starts here!!!"); _another.AnotherFunction(); await Task.Delay(1000, cancellationToken); _exitCode = 0; } catch (Exception ex) { _logger.LogError(ex, "Unhandled exception"); _exitCode = 1; } finally { _applicationLifetime.StopApplication(); } }); }); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _logger.LogDebug($"Exiting with return code: {_exitCode}"); Environment.ExitCode = _exitCode.GetValueOrDefault(-1); return Task.CompletedTask; } } 

AnotherClass.cs

namespace RedBeans.Examples.Console.DependencyInjectionLoggingExample; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; internal class AnotherClass { private readonly ILogger _logger; private readonly IOptions<ConfigSection1Settings> _configSection1; public AnotherClass(IOptions<ConfigSection1Settings> configSection1, ILogger<AnotherClass> logger) { _logger = logger; _configSection1 = configSection1; } public void AnotherFunction() { _logger.LogInformation($"I can tell you the value of configSection1.Config1 is {_configSection1.Value.Config1}"); } } 

ConfigSection1Settings.cs

namespace RedBeans.Examples.Console.DependencyInjectionLoggingExample; internal sealed class ConfigSection1Settings { public string? Config1 { get; set; } } 

appsettings.json

{ "Logging": { "LogLevel": { "Default": "Debug", "Microsoft.Hosting.Lifetime": "Warning", "Microsoft.Extensions.Hosting.Internal.Host": "Warning" } }, "ConfigSection1": { "Config1": "Value1" }, "NLog": { "throwConfigExceptions": true, "targets": { "async": true, "logfile": { "type": "File", "fileName": "c:/temp/nlog-${shortdate}.log" }, "logconsole": { "type": "Console" } }, "rules": [ { "logger": "Microsoft.*", "maxLevel": "Error", "final": true }, { "logger": "*", "minLevel": "Info", "writeTo": "logconsole" }, { "logger": "*", "minLevel": "Debug", "writeTo": "logfile" } ] } } 

Project File

<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" /> <Content Include="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <PackageReference Include="NLog.Extensions.Logging" Version="5.0.1" /> </ItemGroup> </Project> 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like