.NET Core Console App Set Up


| June 8, 2021 | in

.NET Core has changed things quite a bit from the old .NET Framework days. While it is really easy to look at a .NET Core console application and think it is pretty much a .NET Framework application, there are potentially many differences.

In both .NET Framework and .NET Core, you can quickly just create a console application. But where it gets interesting is if you want to access many of the new features available in .NET Core. For example, if you want access to .NET Core’s dependency inversion (Service Collection) features, you are going to have to do a little more work — and your simple console application won’t be so simple. Another good example would be accessing a database. If you want to access a database, you may want to make some extensions to the code provided in this blog post.

In the following activity, we are going to configure a .NET Core Console application to run with dependency inversion, configuration, and Entity Framework — all things you would likely want in a console application (Note, we won’t use Entity Framework in this example).

Step 1. Create a console application

In Visual Studio, you can do this with File | New, or you can use the dotnet CLI command “dotnet new console”.

Step 2. Add some NuGet package references

This can be done with the CLI command “dotnet add package ” or using the Add Reference dialog in Visual Studio.


Step 3. Update our Program class

An out of the box Program class would look like this:

But we need to make some pretty big changes here. First, we must make the Main method an async method. Second, we need to create a new property to initialize the host “CreateHostBuilder”. A lot of work occurs here. We are initializing how we interact with configuration, and we are configuring some of our services.

Step 4. Put our code into the ConsoleService class

The ConsoleService class will be where we put our code that would have previously lived in our Main method.

Why would we go through all this effort? Feels like a lot of work, right? Very true. Lots of code for a console application. But we now have dependency inversion set up. We can read from configuration files. While it’s a lot of code to achieve this, it is a good starting point for writing a console application. In the next blog post, we are going to parse a list of contacts and inject them into a database.

Related posts