.NET 5 Console App with Dependency Injection, Serilog Logging, and AppSettings

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello friends thank you for watching this video i am muhammad and today we will be building a dotnet core app which support dependency instruction serie lock logging and app setting configuration please like share and subscribe if you like this video it will really help the channel so what are we going to be covering today first we're going to be discussing the development ingredients which is going to be the tools that we need in order for us to jump start into development then we're going to be discussing some of the functionality that we're going to be building and lastly we're going to start coding so what are the ingredients basically we need two things visual studio code which can be freely downloaded through the link that's available on the screen i'll also add those links in the description down below as well we need the network sdk which is also can be freely downloaded through the links next we're gonna be developing these three main functionalities to our console application first we're going to implement dependency instruction then we're going to be adding serilock logging in for it to replace the default logs that the framework provides that not core frameworks provide and lastly we're going to be reading all of our configuration from the app settings instead of hard coding them into our code let us start coding the first thing we're going to do is we're going to check if our.net core sdk has been installed successfully in order for us to do that we need to type dotnet dash dash version and as we can see we have the latest version installed which is 5.0.201 if you see any other number that should be okay if you see any error message you need to re-download and install the sdk again now we're gonna start by creating our application inside our terminal for to do that we're gonna be utilizing that not the new keyword so dotnet new console and we're going to give this application a name sample up this will take a few seconds perfect now it has been created successfully let us navigate to it and let's open it inside our code editor which is going to be visual studio code perfect the first thing we're going to do is we're going to open the terminal we have to go to view and we can see we have terminal here and now we have the integrated terminal inside visual studio code we're going to start by building the application to make sure it's building successfully so dot nut build and this will also take a few seconds and we can see it's building succeeded now let's try to make sure that we get the hello world dot not run and we got the hello world perfect so once we have done that the next step is for us to add some of the packages that we're going to be utilizing in total we're going to have four packages and let's start adding them so it's going to be not add package the first one is going to be microsoft dot extensions dot hosting this should also take a few seconds the second one is dot not add package serilog dot extension dot hosting also this will take a few seconds then we're gonna be adding also serilog which is dotnet add package celli log dot settings dot configuration and lastly we're gonna add dot nut add package sirilog dot syncs dot console perfect now these four dependency or four packages been installed we can verify that they are installed by going to our sample app cs approach and once we open it we can see that we have the four packages installed there perfect so the next step for us is we need to create our app settings.json in order for us to do that inside our root folder we right click new file settings dot json perfect and now we need to start populating our app settings so we can utilize them with our sample code that we're going to be creating as well as with cellulog so what we're going to do first is we're going to be adding the serilog configuration so called serilog and then we're going to be specifying the minimum level so that mean the minimum level of logs that we want to display so by default we're going to be displaying full testing information is the information level and we're going to override them on two items so override for system was gonna be on warning and for microsoft it's gonna be on information as well let's add a dummy connection string for now uh we'll call it default connection and let's give it any random connection data source for sqlite call it updb for example and let's make it cache equal shift that sample one will not kinda really use it we're just gonna see if we can implement it within our dependency injection so what does minimum level mean default mean and override here mean so basically the minimum level means that what is the minimum level of logs that we want and we can have information we can have debugging we can have errors for this sample application we're gonna go with information level and we're gonna uh the reason that we added over right here to display how we can override some of the configuration for cellulog so we said although we want all of the information that is gonna be log on information level we're going to override this configuration only for two so we're going to be overriding here only for two namespaces which is the settings and microsoft we can have a lot of different namespace namespaces but right now because only these two name spaces that we want to override so for example let's say we were using entity framework for example if we put for example if it's going to be under microsoft so for example you can put microsoft dot efcor for example and we can put here only on error level on error so that mean only the errors that's popping up of entity framework namespace is gonna show uh so for this reason we only and input here the namespace and the level that we want to log for that namespace in specific great so once we have added those our next step is to actually start building our application so let's navigate to our program.cs and inside here we're going to start adding our configuration methods so that configuration methods that we're going to add right now is going to be responsible for reading the app settings and actually make it available so let's start by creating a new method it's going to be static void and we're going to call it config setup and it's going to take an eye configuration builder of builder and let's fix those references and now let's use builder dot set base path basically we're telling it where to find this file and now we're telling it that it needs to find it from the root folder so directory dot get current directory let's also fix those references perfect then we're gonna tell it to read the json file so add json file and then we're gonna be providing the name for it so it's gonna be appsettings.json and then is it an optional file of course we don't want it option it has to be there so we're going to put optional false and do we want it to reload on change so if we do any changes to the app system things do we want to reload those configuration yes so we're going to put reload on change we load on change gonna put to true and lastly we're gonna add the add environmental variable so let us summarize what we did here so we added a new method called config setup which is going to be basically able to read the application settings file that we have created and the first thing is setbasepath we're just turning it where should it find that the directory we should find that file second we're gonna telling it what's the name of the file that it needs to look for and if it's gonna be optional to finding it and does it need to reload it every time we do chains for it and lastly if we're saying if we have environmental variables that we need to take into consideration so sometimes for example we can add uh dotnet for example i think scrollvar and we can set up the environment the secrets and key that we want and that's gonna be a environmental variable which is not gonna be available within app settings but it's gonna be available on the os level so and those uh environmental variables can override the application settings that we have so for example if we have a connection string inside our app settings and we add another one inside our for example environmental variable the one within the environmental variable will be more will take priority over the one within our app settings and for this reason uh the application will run basically only on the environmental variables for this reason we have added it but uh if you don't want you don't really need to edit it it's just like a good practice to have it there so once we have that ready next step is we need to build our startup methods which is going to be basically making the startup class in an asp.net core application so this method also going to be static it's going to return an i host we're going to explain that later why later on and we're going to call app startup perfect so the first thing we're going to do is uh we're going to define the first hat as fixed references and then we're going to be starting to find our configuration builder so var builder equal new configuration builder perfect and now we need to utilize the config setup that we have before and add the builder to it so config setup and we're going to activate the builder so now we have initiated a configuration builder that's provided for us by asp.net core and we are passing the builder here in order for it to be automatically set up the next step is we're going to be defying the serial configuration so defining serilog configs we're going to start by log dot logger this is a serilog method so let's put using serilog and from that on equal new logger configuration and these are silly log configurations we're gonna start by uh reading from so we're gonna tell it where where is it gonna be reading its configuration from so we're gonna say read from dot configuration and we're gonna use the builder dot build so what we are telling sirilog here that you need to go to the builder that we have here you need to check uh where is it getting its configuration which is gonna be app settings and it's automatically gonna be injecting all of this configuration that we have added in the app settings.json into the serialog configuration builder and then we need to add an extra configuration which is going to be in rich dot from lock context which is gonna give us a better uh output a better information about the locks that we're getting and then we're gonna decide where are we gonna be displaying these logs so we're gonna put try to to right now we're gonna only be displaying out of the console and finally we're gonna create that log logger so we're gonna create logger and that's it so let us do a quick summary about this because there's a lot of stuff here to unpack the first thing is we have defined the new logo configuration for serilog we're telling it we're gonna giving you we're gonna give you default uh new log new configuration for your logger uh the second one is we're telling it where it needs to read all of this configuration so we're telling it that it needs to go to the configuration builder and read it directly from there and then we're giving the logger more information of how it should display the output for us so we suddenly you need to enrich that output by giving us more information and then we're specifying that we need to write the console so we need to display those logs into console we could we can change it here for example from console to for example we can add it to a elastic search we can add it to a text files we can do a lot of different configuration but simply for the simply simplicity of this project we're just going to do it directly in the console and lastly we are initiating the logger great so next step is we're going to be defining our dependency injection model so how are we going to be doing that let's create a host equal host dot create default builder and basically here we are initiating a host so if you look at it what does it do it initiates the host builder which base which basically means that it's uh utilizing the default dependency instruction framework that asp.net core provides and then we're gonna be doing configuring services configure services and these configuration services here if you if you have worked with asp.net core before you know in the startup class we have the configure services method here it's going to be the same thing so this is basically we're going to create a method out of this and then we are able to add all of the services that we want to inject into our dependency instruction so let's do two parentheses and let's create the context as well as the services and then let's create a method and from here for now we're gonna leave it empty because we don't have uh our classes and uh interfaces that we wanna inject but we're gonna come back to this later on and add for our dependency injection and after that we're gonna be excuse me after that basically we're gonna just uh tell it to use serilog so use cellulog and lastly we're gonna just start it to build this configuration to to build this builder so build perfect so once we have added those the last thing we need to do is we need to return the host so we can utilize it within our main method later on so this is also a very simple update a very simple method let's do a quick uh overview of what we did so the first thing that we did is we have created a configuration builder and we have uh passed it to the config setup method that we have provided earlier so it will be able to read the application settings then we define in the sirilog configuration then after that let's add a command here initiated the eye container dependency injection dependency injection container for us to use and lastly we have returned the host which is going to be the ihost perfect now once we have implemented these let's see create an interface and let's include a class and let's try to inject those so first let's create the interface and we're going to call this interface and i i database service data service and this interface can have only one method it's just a very simple method called connect so to avoid to a mimic we are connecting to a database and then we're going to create another class which is going to call the data service and this data service is going to inherit from the i data service sorry it's going to implement the idata service and now let's build this data service so first of all we're going to be adding the loggers and the configuration to it and then we're going to be implementing the connect method so first going to be private read only i logger because we want to log what was coming out of this service so we're going to put data service and we're gonna call it underscore log and then go private read only i configuration and this is gonna be underscore config and here let's use the extension let's define the fixed references perfect now let's create our constructor and it's going to be i logger of data service call it log and for the configuration as well it's going to be i configuration i'm going to call it config and then here all we need to do is just oh let's remove this one we don't need it it's gonna be log equal log and underscore config equal config perfect so now we have injected these two methods directly into our constructor now we can define the method that we had which is public void connect and then here basically what we're going to do is first we're going to be reading the connection string so if we are able to read that connection string it means that we are able to connect directly to our app settings through dependency injection which is what we need and secondly we just want to log that information out on an information level and basically here we're trying to mimic if it's actually connected to the database without actually connecting we're just reading it and mimicking that functionality if you want so we're gonna using the logger and we're gonna put log information and basically we're just gonna give it the connection string and let's make it a cs and here we're going to be defining the conduction string so first let's get this connection string so it's going to be var cs equal we're going to directly read from the configuration and then we're going to utilize the gut value and we're telling it that it needs to be a string value and then after that we're just basically defining how does it where does it lay inside the app settings and with this structure so if we go back to our app settings.json we can see that we have first the connection strings and then we have the default connection so we need to respect this hierarchy so once we come back here we need to put connection strings and then we need to put colon for the hierarchy and then it's going to be default connection once we have those all we need to do is add here the cs which is going to be the connection string that we were going to log out perfect now we have added these now let's update our startup class uh our actually our startup method here in order for us to utilize the interface and the class that we have just created so how do we do that all we need to do is inside our host builder as we need inside our configure services we need to create a transient service for it to automatically pick up the idata service as well as a data service so how do we do that it's very simple we're just going to utilize the services dot add transient let's fix those references and then all we need is we're going to pass the interface which is going to be i data service and then we're going to pass the data service and we're gonna give it this way and we're gonna yeah so why did we use transient basically transient means that every time a new instance is requested a new object is generated for it as simple as that we can do add scoped for example but i think for right now for to better for this sample we're going to stick with transient perfect once we have added that now let us build our app settings uh sorry our main functionality we don't really need this function anymore let's remove it and let's start implementing so the first thing we're gonna need is we're gonna need uh the host so we're gonna be referring to the app startup class so we're gonna call it var host equal app startup perfect so this is gonna provide us the host with all of the configuration so and after that we're gonna be uh utilizing that service so basically now we wanna utilize the i data service but you might ask how are we gonna be referring to that i data service because if we see from the configuration of the data service it's gonna require the a logger and it's going to require the configuration and we don't really want to do all of the money we'll work here to provide that with it so how can we fix this issue it's going to be very simple we're going to just put var and we're going to call it data service and equal we're going to utilize something that that not going to provide for us which is going to be activator utilities dot create instance create instance and we're going to define what type of instance do you want to create which is going to be the data service instance and then we're gonna give it all of the dependency injection that we have automatically initiated inside our app startup so we're gonna put host dot services and once we have that all we need to do is services so actually it's going to be data service dot connect so let us explain what happened here so the first thing that we did is we just called our startup function and the startup function as we have mentioned before it's going to do all of the wiring for our configuration for our dependency injection and all of those and for the logger and it's going to turn for us on ihost so once it returned for us the host we want right now to utilize the data service but the data service as we have as well discussed it's going to have some dependency inside that it's constructor for it to load so what we could have done is we could have said for example for example var log equal new logger and it's going to be basically having those and we can inject them in the data surface but that's not the way to do it we want to utilize dependency instruction to handle this and one way to do it is utilizing the activator utilities so since we have already have the app startup with us and we have already initiated all of the dependencies here inside the services we have automatically initiated the service and right now our dependency injection has automatically created the configuration it has automatically created the loggers instances we don't really need to do all of this work all over again so for this reason what we did is we utilized activated utilities was microsoft provided for us within the dependency injection package and we're gonna we're trying to create an instance for data service and automatically give it all of the dependencies that it needs from the services that we have so what this method is going to do is going to look inside the data service and check inside the constructor what does what does it need so once it goes there it's going to check okay it's going to need a ilogger of data service and it's going need an eye configuration and because we have already initiated them inside the services it's gonna say okay i have those and basically here within those two parentheses those services that we have already provided are automatically instructed inside inside this data service perfect and now we have our data service ready and lastly basically we're just initiating the method that we have which is connect for this data service now let's run it first let us build it to make sure that we did not break anything so do not build perfect build succeeded now let's run it and now if this all is successful we're going to be seeing the connection string popping out on the screen so dotnet run and perfect we can see that the log is being shown based on the information level that we have specified in our app settings and we can see that our connection string has been shown up with this data source app cache shared which is exactly what we have inside the app settings so in summary what we did is we have added the app settings to to the application and then we have configured the config setup to read it and make it available for our application and then we have passed it to the configuration builder then we have created the serilog logger and we did it we gave it all of the right configuration we created the dependency injection and we gave it also all of its required configuration and lastly we created one data service with an interface and then basically we injected or we initiated this data service using dependency instruction and we made it run thanks a lot for watching uh please like and share this video if you find it helpful please if you have any questions or any suggestion about topics that you would like me to cover please write them down in the comments down below the source code will be available on github and the links for this will also be available in the description down below have a good day
Info
Channel: Mohamad Lawand
Views: 9,886
Rating: undefined out of 5
Keywords: dotnet, c#, beginners, step by step, dotnet 5, .net 5, serilog, logs, appsettings.json, dependency injection, di, console, console app
Id: 4mEN1XpLN_s
Channel Id: undefined
Length: 29min 11sec (1751 seconds)
Published: Wed Mar 24 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.