Sunday 31 January 2021

Part 18: DI services (Singleton, Transient and Scoped)

#10 minutes of reading

 

I’m using same sample created for DI article (part 17). Dependency injection provides three ways to register service and based on the selected way life of service decide. 

DI provide below three types

        1.       Singleton

        2.       Scoped

        3.       Transient

Singleton, Scoped, and Transient are three different ways in Asp.Net Core which helps to configure service with object lifetime, it means Singleton, Scoped, and Transient are used to decide how long object available or life of an service(DI configured service). Let’s understand with an example below.

 

Singleton: Object created only once and throughout application that same object is reused. This is same concept from Singleton design pattern. Let’s understand with an example.


 

Update create view of student controller

Add below highlighted line in create view of student controller.

Run application and you observe each time you add employee, it shows employee count increment  by 1 correctly.

Each time I click on create; count will increase. Count is nothing but total number of employees and when I click on create in background, I’m adding new employee to existing object and object persist throughout the application in singleton and return updated count of total number of employees.

 

 

Scoped: In this type, new object gets created for every pair of http request. Let’s move to visual studio and check how it works.

Open Startup file and modify service type to scoped shown below.

Run application and check in browser.

First time count is 2, as 2 records already available in list object. Click on create the count will increase 3 again click on create but this time count is 3. Whenever you create http pair of new requests it creates new object of type service StudentRepository. No matter how many times click on Create button but count always three after click on Create button.

Transient: Object gets created each time service gets called. Lets check in visual studio and modify service type to Transient in ConfigureServices method of startup file shown below.

Run application and check in browser.

No matter how many times click on create button but count should be 2 only as transient create new object each time we request.


Previous                                                                                                                                                Next

Part 16: Model binding and exchanging data between view and model

#10 minutes of reading

 

In this article, I will explain model binding concept of MVC, frequently used concept while passing data from view to controller. I have provided link for MVC 5 article, as most of the concept of MVC 5 from old framework and MVC in Core framework are same. 

 

Create Asp.Net core 3.1 project using MVC template and add Employee model class in Models folder.


Add controller with name Employee and add create action method with name shown below. 


 Right click on create action and add view and click on Razor with below highlighted options.


Create view rendered with the help of MVC scaffolding. 


Run application and check on browser window.


Highlighted is create view from browser but when you put some data and click on create button nothing will happen, because we created Create action method in Employee controller for displaying Create view shown above, but not handled or created any action to handled post request. To complete post request from above view to server , create one more action method with [HTTPPost] attribute.

 


Run application, type below highlighted controller and action name (Employee/Create) and observe employee property showing for Post Create action method.

You can write property names directly from Employee model as parameter to create action method shown below.

 


It is recommended to use Post action([HttpPost]) instead of Get action while passing data (saving data to database) from view. Let’s check what is the issue with Get request. I have modified below Create action methods to produce below scenario.

Run application enter below URL highlighted, click inside URL textbox and press enter, make sure you do not press create button. Click inside URL after entering URL and press enter. This time request will go to HttpGet of Create action method and notice its shows EmployeId highlighted below. If you use Get method to store data, hackers get benefit to crack your application. Always use Post action to pass data from view to browser.

 


  

Please visit my MVC 5 bog for passing data from controller to View using ViewData, ViewBag and TempData from here. Most of MVC concept are same in old and new .Net framework.


Previous                                                                                                                                                Next

Saturday 30 January 2021

Part 17: Dependency Injection in Asp.Net Core 3.1

#15 minutes reading

 

In this article I will show you how dependency Injection works in Asp.Net Core. Dependency Injection Principle is one of concept/principle from SOLID principle. Sample code available on GitHub

 

Dependency Injection principle talks on loose coupling, Low level (Data access logic, Business logic, …etc) objects not directly depend on high level object (controller, Views, …etc) but on abstraction. Means dependency injection is adding a layer between High level objects and low-level object and the layer is nothing but abstraction. Dependency injection provides better maintainability, reusability, and testability.

 


Will understand Dependency injection with above real time scenario. In above screen there are two types of mobile charger one without USB connection and one with USB connection.

Charger without USB connection: Suppose cable gets damaged you need to replace complete charger in that case. To connect your phone, you need to purchase another cable. So here cable is directly connected with wire.

Charger with USB connection: Suppose cable gets damaged no problem purchase cable and use charger no need to bye new charger with cable. Same cable used to connect with laptop for sharing data, reusability comes here and better maintainability. 

Same concept apply with Dependency injection, lets understand with below screen.


If you choose tight coupling, where low level objects (Entity framework, Plain Ado.Net) directly depend on high level objects. To access Database related functionality in Controller, need to create an object of Data access layer class to access members from class and creating low level objects directly on high level is called as tight coupling.

 


 

On the other hand, loose coupling works very smooth and interface work as mediator between high- and low-level object. It gives you better maintainability, reusability and testability. Suppose My SQL is you primary database and after few year database migrated from My SQL to MS SQL server, Oracle, or Mongo Db in that case you just need to replace your Data Access Layer(My SQL) and Plug-in Data Access Layer (MS SQL Server). If you wants to test your controller action and Data Access Layer is not available or someone else performing testing of Data Access Layer in that case based on interfaces database Mock classes will be used for testing controller actions. 

Now you understand the benefit or loose coupling or dependency injection. 

Asp.Net Core by default support dependency injection with IOC (Inversion of Control). It’s nothing but a container or a place where you need to register Interface name and dependent object name and container from DI manage creating an object on the fly.  

Let’s create Asp.Net Core application using MVC template.



Create model class with name Student.



Now I’m creating models in same project but in real time project good if you create separate project and maintain model there. Also, separate project for writing DB functions like reading student data from database, modify Student data, …etc.

 

Create StudentRepository class inside Model folder. For now I’m creating everything in Models folder, as we proceed to through the course I will show you how we can break and maintain in multiple projects. 


Now we have interface with name IStudentRepository and class with name StudentRepository. Our goal is not to use StudentRepository directly in High level and user abstraction (IStudentRepository).

Open startup.cs file and register low level class with interface.


We have register service (IStudentRepository) and implementation (StudentRepository) successfully using DI (dependency injection).

Create strongly typed view for Index action of Student controller.



 Index view created successfully, now run application and check browser window.

 


Update Student controller for Create student action method shown below.


Create strongly typed view using MVC scaffolding shown below.

Now run application and check browser windows and click on Create New action link on browser.



Click on Create button to add new employee

 




Let’s add few more student using Create New Action link from above screen.




Previous                                                                                                                                               Next


Friday 29 January 2021

Part 15 : Tag Helpers

#10 minutes of reading 


Before digging more on tag helper I will suggest to go through my blog on Layout and Viewstart Views.

I hope you go through the Layout and ViewStart views blog, lets understand ViewImports view now.

_ViewImports already available under Views folder of Asp.Net core project. This file is used to import namespace required for views which are created under views folder.

 

Tag helpers introduced with Asp.Net core 1 it is very much similar in Html helpers from previous version of MVC from old .Net framework. According to Asp.Net Core official article, Tag Helpers are server-side code enable to participate in creating and rendering HTML in Razor view.

 

Create Asp.Net Core 3.1 application with name TagHelpers using MVC template. Refer Part 12 for more information on creating Asp.Net Core project using MVC template. Code available on GitHub



By default ViewImports view has few namespace imported. View under views folder directly access model from Models folder without referencing namespace as namespace already referenced in viewimport view.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers  referenced in viewimport shown in above screen is namespace for Tag helpers.

 

Let’s understand with example. Create controller with name TagController.


Now create model with name Employee shown below.


Right click on Index and create Razor view with below option.



Run application and enter Tag controller in URL shown below.


You noticed Tag helpers is different than HTML helpers Syntactically but achieve same purpose of rendering HTML from server side. With Html helpers altogether different syntax but tag helpers are extension of HTML tag as you can see above scree.

Now let’s compare Tag helpers against Html helpers.  Let’s delete everything from Index view after line number 7 shown in above screen and update below piece of code in Index view shown below.



I have shown both Tag helpers and Html Helpers as you can see both are syntactically different and Tag helpers more of like Html tag or extension of Html rendered from server side.

Right click on browser windows and select View Page Source.



Both rendered plain html on browser shown in above screen. Main different between Html and Tag helper is syntax.

It is recommended to use tag helpers or Html helpers rather plain Html in MVC framework. Lets understand why?

 

Add below piece of code in Index view of Tag controller and remove existing piece of code from Index view of tag controller.



Run application and check browser window. 



Both link from browser will navigate you to Index view of home controller. Now we decided to modify domain name or append name in URL. Open Startup file from project.



Now append some text in URL name. Check Route configured for pattern highlighted below and run application.


Click on action link highlighted above and check browser window.



Press back button from browser and click on second action link from index view of Tag controller and check browser.

 


If you use html anchor tag for navigation and later you modify or append text in route, in that case you need to visit all anchor tag in application and append text before controller name. But you go with Html helper or tag helper framework automatically handle it. Also Tag or Html helper is used for Rapid development.

 

Note: For Image Tag Helper, unique version number generated from server side and browser gets latest image instead of taking image from cache, as version number compared and after image gets change on server side the updated image automatically rendered on browser when perform next http request. Visit here more details

Visit here for more Tag helpers and scroll down to check below section from official website.



 Previous                                                                                                                                        Next

Thursday 28 January 2021

Part 14: Routing in Asp.Net Core 3.1

#10 minutes of reading

 

In this article I will show you routing in asp.net core 3.1 with route constraint. I’m using application created under Part 13 and code also available on GitHub.

Routing in Asp.Net core is slightly different as compared to MVC 4/5(old .Net framework). Here no concept of RouteConfig file but middleware is replacement for RouteConfig.

Open Startup file from project, below highlighted middleware is responsible for routing in asp.net core application.

As discussed in previous article actual execution of route performed by UseEndpoints middleware. Default MVC project template in core uses MapControllerRoute method above highlighted. Here you can configure routes for an application.

Name of route is default and pattern are {controller=Home}/{action=Index} /{Id?}

Question(?) at the end of {ID?} represent Id is optional in route and by default if no route (controller name and action name) mentioned in URL by default it routed to Index action of Home controller.

Run application it will render Index action of Home controller and check URL controller name and action name is missing and default it rendered for Home controller. 

Let’s add action method which accept parameter in HomeController.

As shown in above screen, in configure method parameter name is id and in actual action method (Test) of home controller I declare variable with name in this case it won’t work.

To fix this need to change name of variable on Test action method or rename Id to name in configure method. Let’s update Test action method and check again.

Route Constraint:

Suppose requirement of accepting only integer numbers as parameter and restrict string in URL. This concept called as route constraint.

In StartUp file, I have added one more route with name IntParameter which accept only integer as parameter and ignore alphabates or alphanumeric and convert param value to null if it is not integer value. In above scenario for ‘asif’ its text and it gets ignored and becomes null.

Now pass integer from URL and check Test action method of HomeController again.

You shock to see, its returning 0 instead of 3. Now look at the route in above screen from StartUp file, incoming route validated against configured route. Route default is on top from configured route, when incoming request come it first validated with default route and it matches with default and ignored id parameter. If Id parameter not matched it ignore value and make it zero for int and null for string.

 

To fix this rearrange route in startup file shown below and run application again.

Also, we saw more than one route is supported in MVC if you create one more action method with name parameter it will match with default route and work as expected. Hence incoming requested route validated against route configured and return response.

You can also achieve if requirement is to pass text (A-Z, a-z) parameter. It won’t support numeric inside else it makes parameter null. Let’s understand with below example.

Asp.Net Core allows us to create route with same name highlighted above but good to create route with unique names. 

Regular expression as constraint in route. Create Test4 action method in home controller and RegEx route in startup.cs file shown below.


Previous                                                                                                                                                 Next