Creating a C# console application with dependency injection

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
I'm Dominic Cronin and in this video I'm going to show you how to make a console application in Visual Studio in C sharp with dependency injection let's get started by going to visual studio I'm opening up visual studio 2022 latest version and I'm going to create a new project and what you can see here is immediately interesting you've got various kinds of templates that are available that will produce the scaffolding for for the different kinds of applications and so for example if you were to choose asp.net core web app it would create an asp.net core web app with all the dependency injection wired up and ready to go unfortunately if you create a console app that's that's not the case so let's just create one and you can see I'm using.net6 and uh with top level statements you could also do this without top level stains but uh that's actually does allow us to see the uh very Bare Bones nature of the console app so I can run this and it doesn't do anything much except output hello world to the console hurray okay so yeah why do I want to add dependency injection I find is that I use console apps mostly if I want to test out a bit of code or try out a new idea or something and and sometimes you can find you you've gone quite a long way along the road before you realize yeah okay now this is this is something that I want to do and I want to transfer this code into uh into real application maybe you've written a class that's useful and so it's handy if you've written the class from the beginning with the Assumption of dependency injection so that you're not creating the dependencies in the class but injecting them from outside and you're sticking to the the disciplines that you want to stick to normally when writing code it allows you to add unit tests whatever the rest the good news is it's actually really easy to do so um let's have at it so let's imagine that in my application I've decided I want to have the main functionality of the application be hosted in a class called application so I'm going to create a Services folder not necessary but this is the convention this is where we typically put service classes and I'm going to add a class add a class and yeah for this demo that's going to be called application and then what's the minimum I can do public void run [Music] so I'm going to make a run method and the run method and I'm going to just pick up this so console line in the run method I'm going to add a console right line and here I'm going to say from application class the application class Okay so this is the line of code that I actually want to have executed this will show me that that I've um I've managed to uh get the app get this application class up in the air fire dependency injection and then execute some coding it so I'm going to at this point I'm going to add an interface it's not strictly necessary you can do this without an interface but the standard convention is we work with interfaces so I'm going to let it create the default I application I'm going to say add it to the current file so now I have an interface and I have an application class so let's go back to the program file so I'm just going to leave that console line there and then uh two things that I need to add in the dependencies of the application itself so let's go to nuget manage new get packages and of course there's various ways of adding new get packages but we'll just go here because it's uh that's how I usually do it and I'm going to say let's have a look and see what packages I need to add the packages that are interesting for this are in the Microsoft dot extensions namespace [Music] and the first the first one we want is this one Microsoft dot extensions dot dependency injection so not any other variations on a theme this is the one we want microsoft.extensions.dependency injection that should be easy enough to remember and the other one we want is also in the Microsoft extensions namespace and it's called Microsoft extensions.hosting again there are various variations on a theme here but this is the one we want microsoft.extensions dot hosting install that one too and now we've got everything that we need so having added that we now have access to a class called host and unfortunately Visual Studio is very clever and it will add the namespace for me if I let it yeah there we are see it's added the namespace here and what I want to do is I want to get a host so it implements the I host interface I'm going to say host Dot create default Builder and this is a very interesting method this will set up the default host builder in my.net 6 application and if I hover over it you can see that it does a whole bunch of really interesting things is going to set set it up with with pulling in configuration from various sources from an app settings file or from the environment variables or whatever very useful and it's also going to set up the ilogger factory and I'm going to use that later in the in the demo so what I'm going to do now now that I have a builder I'm going to say configure services okay and it immediately offers to create a Lambda for me which is nice and then once you've done the configuring of services you need to call Dot build or you might change various other methods in here but for now you 've got and that gives us then an eye host back so let's have a look what we actually want to do in the services method or the configure Services Lambda and what I'm going to do here is I'm going to say services Dot add Singleton [Music] and what I want to do is say I application and application I hope doesn't try and fill in too much bad text for me [Music] okay let's do that it will it will pull in the up the uh the namespace for me in a second all right sometimes it does it by Magic and other times you've got to do that still whichever way it's still easy than typing all that stuff so so where are we here so I now have um a host which is created by the default Builder and the host is now set up with configured services or unconfigured service what that means is that the dependency injection container has the information available to it so that when I ask it for an eye application it will know to instantiate an application an item of this type and it'll be a Singleton so the dependent subjection also manages the scope of the items it provides you um so all very well I've got a dependency injection container that knows how to do that but I still need to call that method so I still need the object and what I'm going to do here is um I'm going to say Let's uh make an variable for the application [Music] I'm just going to use VAR why not equals underscore host so I've I'm going to the host I'm going to services on the host this is how I get access to the dependency injection container and then I'm going to go oh look it's it's done most of the work for me but I'm going to call uh get required service application it might not do that for you I've typed this a few times on this machine and the um Visual Studio is very clever at learning things so what have I done here I've said go to the dependency injection container and say Yes I want this service and when I say get required service this is similar to get service but if it can't get the service it'll throw an exception for you so that that's the sense of get required service we're going to fail if it doesn't happen um the next line here would oh and look it's already figured out that maybe I've typed this a couple of times before so saves me some typing I'm actually going to call the method on the item on on the the instantiated uh object now if you go to the internet and you look up get required service you'll see an awful lot of chatter about how this method used the use of this method per se is an anti-pattern which of course is nonsense otherwise I suppose Microsoft wouldn't bother putting it in the framework would they there are there's a time and a place to use it when when it's probably a bad idea to use it is in the classes of your application so all of those classes that you're going to bring to life with dependency injection um the whole idea is that the dependencies are explicitly stated and obvious from outside so when we do Constructor injection you can immediately look at the class and you can say these are the things that I need to have injected from outside if I call this method from Insider class and there are occasions when you would want to but few and far between um the uh the idea then of course is that you're reaching into the into the container without it being obvious what you're doing so for a for yourself or another programmer trying to maintain the code it's less obvious what's going on and the the question then is yeah how do I know what I need to add to my to my container to start with how do I know that this is correct in this case well it's fairly obvious because the line that uses it is immediately below but once you get into your application you should have avoid the service locator pattern as such but calling get required service here is not actually using the service locator pattern so so I would argue it anyway I'm not an antiparton this is fine if you if you really want to avoid this then you can do ad hosted service instead of at Singleton but then your application class would have to would have to also have some extra code added to support that and if you're thinking well I'm going to start using my code elsewhere maybe that's not what you want this is this is enough for now and it it should work and I'm actually gonna hit go and we should see both hello world lines hello world oh and something went wrong oh I know what went wrong because what I've done here is I've registered eye application and I've accepted the automatically typed um it automatically typed code from visual studio and it's it's asking for the thing that I didn't register and there you have it that works just lovely I think I'll leave that in nothing like a good mistake um so we have now a working application but it doesn't do much so the purpose behind wanting to to get the application class from dependency injection of course is that when the dependency injection framework instantiate the class for you it's then automatically doing a quick survey of the required dependencies and arranging for those two so that's why we want to ask the container for for the application instead of just instantiating it ourselves then we get the added Services of the of the of the DI framework fixing up the rest of the dependencies so how can we show that well if I go back to create default Builder what it's telling us here is that the um create default Builder also configures the ilogger factory so what this means is that if if I go to my application and I say let's make a Constructor and I say my my class needs an eye logger of occasion [Music] then the dependency injection container created by uh by the default host Builder is already rigged to be able to provide this so let's just say logger and add the read-only field and we can maybe make that a tiny bit tidier by saying just make it a Lambda of it okay [Music] so now I have a field in my class underscore logger which has been dependency injected so I can say underscore logger dot uh log information let's have a nice message coming out here logging application class [Music] anything hello world you should have an exclamation mark and so I'm going to run this now and you'll see that we get three lines of output or in fact four um and there you have it so we're going hello world info logging hello world from the application class and there we are you can also see down here in the output from the deep the debug output that the information logging has also gone to there so that's enough to demonstrate that the Frameworks able to inject other things into my class here obviously I could create more classes register them and also declare those as dependencies here as you would with any uh location of this kind so that was um that was the demonstration it I hope you agree this is actually fairly painless to do and perhaps you'll agree that it's it's useful in that it help it helps us to walk along the road of writing our code in the way we we need to go on and making it easier to transport the code into into other context if we later feel like that and of course I might want to add some unit tests in my console application so this will also support that I'm Dominic Cronin and that was a demonstration of adding dependency injection to a console application in visual studio with c-sharp thanks for watching bye
Info
Channel: Cronin Technology
Views: 4,612
Rating: undefined out of 5
Keywords:
Id: y4BNWvdgccs
Channel Id: undefined
Length: 20min 6sec (1206 seconds)
Published: Wed Oct 19 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.