Overview of Dependency Injection in ASP.NET Core

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in today's video i am going to talk about dependency injection in asp.net core by the end of this video you will know the basics to take the most of dependency injection in asp.net core my name is pat if you are new here consider subscribing because it motivates me to make more videos let's get into it you are looking at a small application written with asp.net core mvc the main page displays the rate of a list of cryptocurrencies and a button to download this list let's take a look at the code the main view is served by the controller name ohm in this controller i use a service name currency service to download the cryptocurrency rate from a remote api the result is limited to 10 records for simplicity creating an instance of currency service with the keyword new in the controller makes the controller strongly couple to the service in a larger application coupling like this can become a problem if we want to test the controller we will have to isolate it from the outside world but with the code as it is a call to the api will be made let's also imagine that we need another implementation for currency service this could happen because we have found a better service for example changing the implementation will result in the modification of our controller and any client code to the currency service in a larger application this will open doors for bugs how can we make our code a little less couple by following the dependency inversion principle the principles state that high level modules should not depend on low level module both should depend on abstractions abstractions should not depend on details details should depend on abstractions this means that how controller should no longer depend on the concrete class lack currency service but rather on an interface and the service itself will implement that interface notice that we invert the arrow pointing to the currency service thus dependency inversions the first step to a losi couple code will be to create an interface for currency service in the currency service class right click on the class name choose extract an interface we will name the interface i currency service click on ok to generate the interface once the interface is created we go back to our controller we replace currency service by i currency service we still have a problem with the creation of the instance we have to find a way to receive an instance of i currency without creating it with the new keywords this is where the dependency injection principle comes into play dependency injection is a technique in which an object can receive its dependency through an injector the injector is also called dependency injection container or di container in short in asp.net core it is automatically provided with the package microsoft.exe injection the most popular way to receive a dependency is to get it as an argument in the constructor let's change ohm constructor we pass i currency service as an argument we remove the new keyword and assign the argument to the currency service variable this change means that a concrete implementation of i currency service will be created by the di container and pass as a constructor parameter how does the dhi container know which implementation to create for a given interface we need to register the dependency with the di container in asp.net core the registration occurs in startup.cs file in the configure service method the service object exposes different extension method for different scenarios we select the add scope method for this interface i currency we want this implementation currency service scope means that the object will be disposed at the end of the request you can manage the lifetime of a dependency with add singleton extension method if you want a shared instance for the wall hub and add transient if you want a new instance each time the dependency is requested we can highlight the three main roles for the di container registering dependencies resolving dependencies when needed and managing the lifetime of dependencies let's run the application to see if it's still working as you can see it works now let's take a look at this download button when you click on it the download method is called it retrieves the list of cryptocurrencies it passes the list to the export method of the csv exporter object in order to export the list as a csv file the csv exporter is a generic class that accept a type and export data of the specified type to a csv file we also have a coupling problem here because we are creating an instance of the csv exporter with the new keyword as in the previous example let's extract an interface from the csv exporter class we name it i csv exporter let's register the dependency in order to register a generic service we are going to use the method add scoped and pass the type of interface as first argument and the type of the implementation as second argument let's go back to the controller to configure the injection this dependency is only used in this method rather than injecting through the constructor we will use method injection in the download method we use the from service method attribute and we pass the i csv exporter interface as an argument let's test the changes in the hub when i click on the download button i receive my dependency as an argument in the download method let's continue the csv file is created i can open it that's how you register a generic service and now you inject a dependency in a method in the following section we will see how to inject a dependency in a view let's add an entry in the app settings.json let's call the key in beta mode let's give the value true this parameter will help display a message telling that the application is in beta let's go to the layout view we will inject an instance of the eye configuration interface in order to read the appsettings.json file the injection is done with the inject directive then next to the title of our application we will add some code to check the value of the in beta mode parameter if this parameter is true we will display a label beta let's run the application you can see that a label with beta is displayed let's change the value of the in beta mode parameter to false you can see that the label does not appear anymore this is how you can inject a service into a razer view you may wonder why we didn't register i configuration in the startup.cs file asp.net core automatically registers some services called framework services this is the case for i logger i configuration and etc the services that we have to register ourselves are called application services that's the one we register in the startup.cs file the currency service uses the http client class to query a remote api for an efficient use of http client we must delegate its creation to the i http client factory interface let's modify the constructor so that it get the http client instance by injection let's go to the startup.cs file in the configure services method we call the add http client method on the service object the first type argument is the i currency service interface and the second is the currency service implementation with this line of code the interface i currency service will be reserved with currency service and currency service will receive an instance of http client so we can delete the previous registration of i currency service let's run the application to see if it's still working the constructor of currency service receive an instance of http client and our data is loaded correctly the configure service method contains three lines of code to register dependencies in a larger application this method can quickly grow and become difficult to read and maintain to avoid this we can group the dependency registration in an extension method let's create a new class name app service registration you can call it whatever you want the class is static let's add a static method named add app services by convention the method extension already starts with hud and then the name of the logical grouping this method will be added to the i service collection interface let's copy the line contained in the configure services method into the new method let's go back to the configure service and replace the two existing line by the add app services method let's launch the app again everything works as before for a given service if there are many registrations the last one will override the previous ones to avoid this we can register a service using the extension method that start with try hard this way a service would be registered only if it doesn't already exist let's run the app again to see if it's works it's still working that's it for this tutorial if you enjoy it let me know in the comment section if you want to support the channel hit the like button and subscribe thanks for watching see you soon
Info
Channel: TechWithPat
Views: 4,368
Rating: undefined out of 5
Keywords: dependency injection in asp.net core, how to use dependency injection in asp.net core, asp.net dependency injection, net core dependency injection, dependency injection explained, asp.net core dependency injection
Id: U4nwjAIeZBQ
Channel Id: undefined
Length: 13min 27sec (807 seconds)
Published: Wed Mar 31 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.