Dependency Injection in Asp.net Core 2.2 (Part 2)


ASP.NET Core is designed from scratch to support Dependency Injection. DI will help the application to create test driven and loosely couple application. This is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.

what are the advantages of Dependency Injection ?
1.Better unit testing.
2. Clean and easy to understand Code
3.better re-usability of code.
4. Loose Coupling application
5. concreate class can be replaced by Mocks

ASP.NET Core framework has simple inbuilt IoC container which does not have as many features as other third party IoC containers like StructureMap, Unity, Ninject etc. For more details please look on below old post

https://chandradev819.wordpress.com/2019/03/24/how-to-implement-structure-map-in-asp-net-mvc-application/

https://chandradev819.wordpress.com/2018/06/05/how-to-implement-the-dependency-injection-in-asp-net-mvc/

If you want more features such as auto-registration, scanning, interceptors, or decorators then you may replace built-in IoC container with a third party container.

What is the IOC Container ?

>> It is the factory class which take care of creation of all object in the system and injecting the right dependencies. It is also called as container.

The container, called an Inversion of Control (IoC) container, keeps a list of all the interfaces needed and the concrete class that implements them. When asked for an instance of any class, it looks at the dependencies it needs and passes them based on the list it keeps. This way very complex graphs of objects can be easily created with a few lines of code.

In addition to managing dependencies, these IoC containers also manage the lifetime of the objects they create. They know whether they can reuse an instance or need to create a new one.

How to Configuring dependency injection in ASP.NET Core ?

We can configure the dependency injection in ConfigureServices method.

public void ConfigureServices(IServiceCollection services) 
{   
// Here goes the configuration
}

In the above method it will accept as type IServiceCollection. This is the list used by the container to keep track of all the dependencies needed by the application. So we have to register the required services in the above methods.

There are two types of dependencies that can be added to the services list.

1.Framework Services: Services which are a part of ASP.NET Core framework.They are usually configured using extension methods like AddServiceName

For example, if you want to use ASP.NET Core MVC, you need to write services.AddMvc() so that all the controllers and filters are automatically added to the list. Also, if you want to use Entity Framework, you need to add DBContext with services.AddDbContext(…).

2. Application Services: The services (custom types or classes or Interface) which you as a programmer create for your application.

Since we are adding them by our-self, we have to also specify the lifetime of service.

There are 3 type of Lifetime of Service

1. Transient : This lifecycle is used for lightweight services that do not hold any state and are fast to instantiate. They are added using the method services.AddTransient(), and a new instance of the class is created every time it is needed.

2. Scoped: This is typically used for services that contain a state that is valid only for the current request, like repositories and data access classes.

Services registered as scoped will be created at the beginning of the request, and the same instance will be reused every time the class is needed within the same request. They are added using the method services.AddScoped().

3. Singleton : IoC container will create and share a single instance of a service throughout the application’s lifetime. Such services typically hold an application state like an in-memory cache. They are added via the method services.AddSingleton().

Demo sample for using dependency injection in asp.net core

Step 1: Create the interface of Service in Service folder of application like this



using System;

namespace HelloWorld_Demo.Service
{
    public interface IClock
    {
        DateTime GetTime();
    }
}

Step 2: Create the implementation of interface like this in Clock class

using System;

namespace HelloWorld_Demo.Service
{
    public class Clock : IClock
    {
        public DateTime GetTime()
        {
            return DateTime.Now;
        }
    }
}

Step 3: Create the blank HomeController in Controllers Folder and implement the constructor injection like this

using HelloWorld_Demo.Service;
using Microsoft.AspNetCore.Mvc;

namespace HelloWorld_Demo.Controllers
{
    public class HomeController : Controller
    {
        private readonly IClock _clock;

        public HomeController(IClock clock)
        {
            _clock = clock;
        }

        public IActionResult Index()
        {
            ViewData["Message"] = $"It is {_clock.GetTime().ToString("T")}";
            return View();
        }
    }
}

Step 4: Create the html view like this

 = "Index";
}

<h3>Demo sample of Dependency Injection in asp.net core MVC</h3>

<p>@ViewData["Message"]</p>

Step 5: Go to the Startup.cs file and Add the Framework service i.e. MVC and Application Service which one we have created IClock as given below


using HelloWorld_Demo.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace HelloWorld_Demo
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Added the Framework Service to use MVC functiionality
            services.AddMvc();

            //Added application services
            services.AddTransient<IClock, Clock>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            if (env.IsProduction())
            {

            }
            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Step 6: Run the application

Getting Started with Asp.net Core 2.2 (Part 1)


Nowadays it is one of the hot topic for Asp.net interview. If you are attaining any interview then they will ask the questions from this topic. So i m going to write the series of post from basic to advance concept on this topic.

Question 1: what is the asp.net core ?

>> It is the next version of asp.net. It is a free,open-source,high-performance and cloud optimized web framework which can run on Windows, Linux, or Mac. This framework is completely rewritten from scratch for building modern, cloud-based, Internet-connected applications

Question 2: Why should we use asp.net core ?

>> These are the following reasons to use Asp.net core
1. ASP.NET Core is faster compare to traditional ASP.NET.
2. Now It is single application for web api and Web UI Layer.
3. Architected for testability.
4. Razor Pages makes coding page-focused scenarios easier and more productive.
5. Blazor lets you use C# in the browser alongside JavaScript. Share server-side and client-side app
logic all written with .NET.
6. Ability to develop and run on Windows, macOS, and Linux.
7. Open-source and community-focused.
8. Integration of modern, client-side frameworks and development workflows.
9. A cloud-ready, environment-based configuration system.
10. Built-in dependency injection.
11. A lightweight, high-performance, and modular HTTP request pipeline.
12. Ability to host on IIS, Nginx, Apache, Docker, or self-host in your own process.
13. Side-by-side app versioning when targeting .NET Core.
14. Tooling that simplifies modern web development.
15. Built in logging support.
16. Environment based configuration supported for cloud deployment.
17. In ASP.NET Core we have middleware which provides more control how the request should be processed
as they are executed in the order in which they are added.

Creating Hello World application on Asp.net Core

Step 1: Firstly install the visual studio 2019 or 2017.

Step 2: Open the Visual Studio 2019 and create the Empty Asp.net core application like this

Step 2: Select the type of project, we are going to create

Now it will create the following files

All files in the root of the project are

Program.cs

>> It is the entry point for web application. Everything starts from here. The .NET Core host can only run console applications. So, the web app is a console application too.

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace HelloWorld_Demo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

This class role is to create the host for the web application. It is the right place to configure the hosting related setting on different server. As you can see in above class which has CreateDefaultBuilder method. Which configure all the services needed for us.

Startup.cs
Asp.net core pipeline start from this file.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace HelloWorld_Demo
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World1!");
            });
        }
    }
}

This class has ConfigureServices Method, where dependency injection will be configured and Configure, where all needed middleware components are registered and configured.

The app.Run method is a perfect example of an inline middleware component.

ASP.NET Core offers an interface named IHostingEnvironment which is used to reads a specific environment variable called ASPNETCORE_ENVIRONMENT and checks its value. If it is Development, it means you are running the application in development mode. If it is Staging, you are running the application in a staging mode. And so it goes for all the environments you need to manage.

We can change the Environment using this file launchSettings.json which will be there in properties folder of application.

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:64471",
      "sslPort": 44320
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "Key": "Value",
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "HelloWorld_Demo": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "https://localhost:5001;http://localhost:5000"
    }
  }
}

appsettings.json
It is similar to webconfig file of asp.net application. Which is used for storing data as application level. We can store the connection string like this

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-2;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Now run the application, we will see the hello world in browser like this