Search code examples
c#host.net-core-3.0

How to and is good practice to create generic Host class extension methods in ASPNETCORE 3?


In typical aspnet core application. As a example of Program.cs

var host = new HostBuilder()
      .Build(); 

   await host.RunAsync(); 

How we must declare if we wish to extend HostBuilder capablites with extension methods as when using "CreateDefaultBuilder()" with IWebHost in netcore <2.2.


Solution

  • To create IHostBuilder extension method.

    Begins creating a static class with static methods (public) Import to the client that is going to use the method.

    Declaration is as follows:

    public static class MyHostHostBuilderExtension
        {
            public static IHostBuilder CreateMyBuilder(this IHostBuilder hostBuilder)
    [...]
    

    In the Program.cs use a HostBuilder() instance.

    var host = new HostBuilder().CreateMyBuilder().Build();
    

    Notice if you using Host static class. It can't be extended.