Dependency Injection in ASP.NET Core
Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at Dependency Injection in ASP.NET Core. It's our 7th tutorial in ASP.NET Core series. In previous versions of ASP.NET, dependency injection was not its core element, although we could have achieved it using third party packages i.e. Ninject, StructureMap etc.
As ASP.NET Core is built from scratch so it was made sure that Dependency Injection should become its essential part. In our previous lecture, we have created Controller & Model for our core project. Now there's a need to connect them together and that will be done by Dependency Injection. So, let's get started with Dependency Injection in ASP.NET Core:
Dependency Injection in ASP.NET Core
- Dependency Injection in ASP.NET Core is used to inject dependencies in Web Application and these dependencies are mentioned in IoC Container, implemented by IServiceProvider.
- In Startup.cs file, the ConfigureServices Method is dependency injection container and if you check it's parameters, then you will find IServiceProvider in it.
- There are different types of Dependency Injections available and the most commonly used one is Constructor Injection.
- In our Startup.cs file, we have seen two Methods: ConfigureServices and Configure.
- So far, we have only discussed Configure Method, which is used to set up Request Processing Pipeline and we add our Middlewares in it.
- But we haven't yet discussed the ConfigureServices Method, which is an IoC Container and is used for service configuration required by our application.
- We can configure both builtin and custom services in this ConfigureServices Method.
- In our previous lecture, we have added an MVC Service (builtin) in this IoC container, as shown in below figure:
- Similarly, we can also create custom dependencies in ASP.NET Core and these custom dependencies will also be registered in this ConfigureServices Method.
- In our previous lecture on MVC architecture, we have created an Interface named IEngineersRepository and a class implementing this interface named EngineersRepository.
- In our future coding, we will never invoke this class, as its an implementation and we don't want to directly call this class as it will make our code rigid. Instead, I will always call this Interface as it's just a definition. ( If you are not getting this point yet, don't worry we will cover it in detail later)
- So, now we have to insert this dependency so that if someone wants to use any method from Interface IEngineersRepository, compiler should know that it has to invoke the method from class EngineersRepository, without actually calling the class.
- So, let's add this dependency using AddSingleton Method, as shown in below figure:
- You can see in above code that in a single line, we have declared our dependency i.e. our interface IEngineersRepository is dependent on class EngineersRepository.
- Now in our project, whenever we invoke this interface IEngineersRepository, compiler will know that I have to look in EngineersRepository class.
We have added the dependency condition in our Dependency Injection Container. But remember one thing that we haven't yet connected Model and Controller. We have just connected a Model Class with a Model Interface. So, now let's have a look at Constructor Injection in ASP.NET Core:
Constructor Injection in ASP.NET Core
- When we want to inject one service into another then we use Constructor Injection in ASP.NET Core.
- The service, we want to inject, is provided as a parameter to the Constructor of the service, in which it is being injected.
- In our example, we want to inject our Interface IEngineersRepository in our Home Controller so that we could use its methods, as shown in below figure:
- I have encircled the constructor injection code with red line, and you can see that I have created the Constructor of Home Controller and then passed interface as a parameter.
- Finally, simply saved the value in private variable _engineersRepository.
- In the action method index(), I have used this variable and then called the method GetEngineers, which is implemented in my class and will provide me the data based on Id, which I have provided 1. ( Rite now value is hard coded, we will automate it soon )
- So, I am getting the university name of engineer with Id = 1, and if you remember we have hard coded the data and the university of first student was MIT.
- So, now let's run this project and if everything goes fine then you will get similar results:
- So, let's summarize our lecture, we have used dependency injection and then called Model function from home controller.
Why we need Dependency Injection ???
- When you are working on some complex application, then we want it to be as flexible as we can and here dependency injection comes quite handy.
- With Dependency Injection, we can bound different parts of our application together.
- Let's say you have created some Interface named "IEngineersData" and then a class implementing it named "EngineersProfile".
- Now in order to implement Constructor Injection, you first have to configure it in the ConfigureServices Method so that compiler could know that this class is implementing that interface.
- In future, if you want to change the implementation of your Interface, you just need to change the name in this IoC Container.
I know it's not making much sense rite now and is a bit difficult to understand, but no need to worry as in our upcoming lecture, we will have a look at practical implementation of these concepts. So, that's all for today, in our next lecture, we will have a look at Views in ASP.NET Core. Till then take care & have fun !!!
Environment Variables in ASP.NET Core
Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to use Environment Variables in ASP.NET Core. It's our 5th tutorial in ASP.NET Core series. In our
Startup.cs file, you must have seen that we have an IF Condition at the start and this IF Condition has
IsDevelopment in it.
This condition is actually checking the environment of our web application. So, here we will first discuss them and then will see why we need them. So, let's get started:
Environment Variables in ASP.NET Core
- ASP.NET Core has 3 builtin Environments, which decides the Run-time operating environment of the web application, which are:
- Development.
- Staging.
- Production.
- In order to set this Environment Variable, we need to open the launchSettings.json file, in the Properties section of Solution Explorer.
- This launchSettings.json file has two profiles in it and both of these profiles have a variable ASPNETCORE_ENVIRONMENT, this variable is used to set the Environment value.
- In the above code, you can see that we have set the value of ASPNETCORE_ENVIRONMENT to be Development, that's why we are in Development mode.
- Let's discuss these 3 environment variables one by one:
Development Environment
- As the name implies, when we are developing the application then we are in Development Environment, so the value of this variable should be Development.
- In Development mode, we can show many details for understanding which we can't directly show to our end user.
- At the start of this Configure Method, you must have seen IsDevelopment, its a builtin ASP.NET Core Boolean function, which is checking the Environment.
- If the Environment is Development then show the Developers Exception Page and as this page has a lot of useful information, we can't show this information to our user, it will be dangerous.
- That's why, we have placed this check that if we are in the Development Environment, only then show this Exception Page. ( We will discuss Exception Page later in detail )
Staging Environment
- When you are developing complex cloud platform web application, then before transferring it to Production Environment, you first have to test it out in Staging Environment.
- Staging Environment is quite equivalent to Production Environment and is normally for QA purposes to have a final look before publishing.
- You can also use IsStaging function just like IsDevelopment in ASP.NET Core.
Production Environment
- When you are fully confident that your application is complete and follows all security protocols etc. then you can set the Environment to Production.
- If you remove this ASPNETCORE_ENVIRONMENT code line from the lauchSettings.json file, then by default, the runtime Environment is Production.
- We also have IsProduction function to use in ASP.NET Core.
Custom Environment
- We can also create a new custom environment in ASP.NET Core, we just need to specify this new name i.e. TEP in the launchSettings.json file.
- Now, in order to check the custom environment, we need to use IsEnvironment("TEP") function, as shown in the code on right side.
- We can use any name for this custom environment, we need to use custom environments in such application where we need to use separate profiles i.e. teacher, student, parents etc.
Developer Exception Page Middleware
- As we have discussed the Environments, so now let's have a look at this Middleware Developer Exception Page.
- It's another builtin ASP.NET Core Middleware, which shows an Exception Page to the Developer, if there's any exception occurs in your application.
- This exception page is very helpful, as it gives detailed information about the exception or the issue occurred in the application.
- We don't want to show this Exception Page to our end user as it reveals a lot of information related to our app, which could be helpful in hacking stuff.
- So, that's why we have placed it inside IsDevelopment condition.
So, that was all about Environment Variables in ASP.NET Core. In the next tutorial, we will have a look at MVC architecture in ASP.NET Core. Till then take care & have fun !!! :)
How to handle Static Files in ASP.NET Core
Hello friends, I hope you all are having fun. In today's tutorial, we are going to have a look at
How to handle Static Files in ASP.NET Core. It's our 4th tutorial in ASP.NET Core series. If you inspect your localhost page displaying Hello World, then you will see that there isn't any HTML code in it. Instead, it's just displaying Hello World in text format.
In today's tutorial, we will have a look at How to add HTML, JavaScript, CSS or any other static file in ASP.NET Core. In our previous tutorial, we have discussed
Middleware in ASP.NET Core, so if you haven't studied that then have a look at it first, as we are gonna use some new middleware components today. So, let's get started:
How to handle Static Files in ASP.NET Core
- By default, ASP.NET Core doesn't allow us to handle / serve static pages and we can add this functionality using Static File Middleware.
- In the Solution Explorer, right click on your Project's Name and then click on Add > New Folder and rename it to wwwroot, as shown in below figure:
- All the static files ( JavaScript, CSS, HTML, Images etc. ) in ASP.NET Core has to be placed inside this wwwroot folder, which is called Content Root Folder, and this folder has to be directly inside the project's root folder i.e. Project's Name.
- Now let's create three folders inside this wwwroot folder for CSS, JavaScript & Images, as shown in below figure:
- In the above figure, you can see that I have created three folders and have also added an image in the images folder.
- You could change these folders' names but its a convention to use these names, it helps in keeping things organized.
- So, now let's access this image in the browser i.e. open this link http://localhost:51640/images/image1.jpg but still you won't get the image, instead it will still display Hello World.
- In order to access this static file i.e. image1.jpg, we have to add a new middleware in the request processing pipeline.
- So, open your Startup.cs file and in the Configure Method, add Static Files Middleware, as shown in below figure:
- You can see in above figure that I have added app.UseStaticFiles() middleware, it's a builtin middleware of ASP.NET Core, which enables the web App to use static files in wwwroot folder.
- After adding this Middleware, now when you open your image link then you will get your image in the browser, as shown in below figure:
Default Home Page in ASP.NET Core
- We can also create a default HTML Home Page in ASP.NET Core using a builtin middleware Default Page.
- This Default Page middleware search for one of the following files in wwwroot folder:
- index.htm
- index.html
- default.htm
- default.html
- If the middleware finds any of the above titled files in wwwroot folder, it will make that file default page or homepage.
- So, let's first create an index.html file in the wwwroot folder, as shown in the image on right side.
- In order to add this index.html file, right click on wwwroot folder and then Add > New Item.
- In the next window, make a search for html page and rename it to index.html.
- Here's the code for that HTML file, I have just added the required HTML along with an H1 tag.
- Now let's add the Default Page Middleware in our Configure Method in Startup.cs file.
- The Configure Method is shown in figure on right side & you can see that I have removed the End Points Middleware.
- Moreover, I have added a new Default File Middleware before Static File Middleware.
- This Default File Middleware doesn't serve the default file itself, instead it just change the request path towards default file, this file is then served by Static Files Middleware, next in the pipeline.
- So, if you place this Default Files after Static Files, then it won't work because files are served first and then default path is set. So, again emphasizing on this point: Position of Middleware matters a lot.
- So, now if you run your web Application, then you will get this index.html file as home page, shown in below figure:
- Now let's have a look at another ASP.NET Core builtin middleware named File Server Middleware.
File Server Middleware
- File Server Middleware combines the functionality of three middlewares in ASP.NET Core, which are:
- Default Files Middleware.
- Static Files Middleware.
- Directory Browser Middleware. ( it gives us information about directories i.e. file no. etc. )
- You can see in the code that I have removed Default Files & Static Files Middlewares & replaced them with File Server Middleware.
Now let's have a look at How to Customize these Middlewares:
How to Customize Middleware ???
- We have discussed it in Middleware lecture that each Middleware starts with "Use" keyword and they are all extension methods.
- Now, in order to Customize these Middleware objects, we need to use respective Options Objects.
- So, let's change the default homepage file to any other file, here's the code:
- After the Routing Middleware, I have created a new instance of File Server Options.
- You can see that, it has the Middleware Name i.e. File Server & then "Options" keyword.
- Similarly, for Default Files Middleware, we have DefaultFilesOptions object for customization.
- After creating the new instance, I have cleared the default file name first and then added a new file name "tep.html".
- You must have created this HTML file in your wwwroot folder, so that File Server Middleware could access it.
- Finally, I have provided this fileServerOptions object as a parameter to UseFileServer Middleware.
- So, that's how we can Customize our home page as well as middleware.
- So, key point to note here is: Middleware starts with "Use" keyword, while its customizing object ends with "Options" keyword.
So, that was all about How to handle Static Files in ASP.NET Core. In the next lecture, we will have a look at this Developer Exception Page Middleware, present at the start of our request processing pipeline. Till then take care & have fun !!!