04 – .NET Core Console Application – Pre Configured Console App
Slide 01
Let’s launch Visual Studio 2019 and quickly create a simple modern Web Application using the project template for an ASP.NET MVC Application.
We’ll call it ModernWebApp to easily identify it while we switch back and forth between this and the Console Application we’ll be building along side of it.
We already know that a modern ASP.NET Web Application is just an old fashion Console Application with some pre-configured defaults.
We know that because of the Program.cs file containing the Main() Method which happens to be the entry point for basically all applications that have the same heritage from C & C++.
Those pre-configured settings can by customized in the StartUp.cs file. Using Dependency Injection we automatically get configuration settings thru Iconfiguration.
In the ConfigureServices method you can customize the pre-configured defaults.
That’s all great and dandy but how do we apply that to a Console Application?
Slide 02
Let’s launch a second instance of Visual Studio 2019 and quickly create a Console Application using the project template for a Command-Line Application.
We’ll name this project Sameworks to demonstrate that a Console Application works the same as a Web Application.
You’ll notice that we have less files but what remains the same is the Program.cs file along with the Main() Method as the entry point.
Let’s take a sample of code from the Modern Web Application to begin building out our “Modern” Console Application.
We’ll create a public static method that returns an IHostBuilder called CreateHostBuiilder. Make sure to pass in any command-line arguments so that they too are available in our application.
Let’s have Visual Studio do some work for us by installing the NuGet Package for the IHostBuilder. We’ll need to install one more NuGet Package for the Host called Microsoft.Extension.Hosting.
Now we can begin the work that will do the work for us. Create a variable that will hold the Ihost Object. Then create a variable that will hold our worker. We’ll do so by using ActivatorUtilities to Create an Instance of our Worker.
We’ll need to bring the namespace for Microsoft.Extensions.DependencyInjection.
We need to also Create our Worker.cs file. We’ll call a method call Run() will needs to be created in the Worker.cs file. We’ll put a simple Console Message saying, “Hello, World!”.
Let’s run it and see if it works!
Low and behold it works!!! We’re off to a great start.
In the next video we’ll look at using Dependency Injection in our Worker Class.
I’ll see you there!