'Where do i put Main method in a console app that uses the "Host.CreateDefaultBuilder(args).Build();"?
I'm creating a console-app following this guide: https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration
- Do I put my Main method where it says "// Application code should start here. "?
- Do I use a Main method, or how do I solve this?
My existing structure:
namespace MyNameSpace
{
public class Program
{
public static async Task Main(string[] args)
{
//application logic......
}
}
}
Solution 1:[1]
You don't need to create an explicit Main
method. C# top-level statements mean that the three lines of code from the tutorial:
using Microsoft.Extensions.Hosting;
using IHost host = Host.CreateDefaultBuilder(args).Build();
await host.RunAsync();
... already form a valid program. It's roughly equivalent to:
using Microsoft.Extensions.Hosting;
class Program
{
static async Task Main(string[] args)
{
using IHost host = Host.CreateDefaultBuilder(args).Build();
await host.RunAsync();
}
}
I'd encourage you to use the existing top-level statement approach unless you need more complexity in your initialization code... although you can write the class and Main
method declarations explicitly if you want to.
Later examples in the same tutorial show larger amounts of application startup code, still using top-level statements. Or you can just create a new ASP.NET Core application which will show more.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jon Skeet |