Different ways to Inject Dependency in ASP.NET Core

In this article, we are going to learn what are different ways of injecting dependency in asp.net core in simple steps.

3 Different Ways to Inject dependency

1 Constructor Injection
In Constructor Injection, the dependency is injected through the constructor of a class.
2 Method Injection (FromServices attribute)
In Method Injection the dependency is injected directly to Action Method using FormService Attribute
3 Dependency injection into views (@inject directive)
A Service can be injected into a view using the @inject directive.

After understanding definition let’s implement it and understand in details how to use it and where to use it. We are going to created ASP.NET Core MVC Application with the name ‘DemoTypesofDependencyInjection‘.

After creating application next we are going to Implement Repository Pattern for doing that we are going to add a folder with name ‘Repository‘ inside this folder we are going to add interface and concrete class which implement an interface.

Code snippet of IProducts Interface

namespace DemoTypesofDependencyInjection.Repository
{
    public interface IProducts
    {

    }
}

Code snippet of ProductsConcrete Class

namespace DemoTypesofDependencyInjection.Repository
{
    public class ProductsConcrete
    {

    }
}

Next, we are going to add Model Product in Models Folder.

Code snippet of Products Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DemoTypesofDependencyInjection.Models
{
    public class Products
    {
        public string ProductId { get; set; }
        public string ProductName { get; set; }
    }
}

After adding IProducts interface, ProductsConcrete class and Products Model let’s declare some methods in IProducts interface.

Declaring Method in IProducts Interface

In IProducts Interface we are going to declare List of Products method which returns a list of products.

using DemoTypesofDependencyInjection.Models;
using System.Collections.Generic;

namespace DemoTypesofDependencyInjection.Repository
{
    public interface IProducts
    {
        List<Products> ListofProducts();
    }
}

Implementing IProducts Interface

ProductsConcrete Class will Implement IProducts interface

using DemoTypesofDependencyInjection.Models;
using System.Collections.Generic;

namespace DemoTypesofDependencyInjection.Repository
{
    public class ProductsConcrete : IProducts
    {
        public List<Products> ListofProducts()
        {
            var listofproducts = new List<Products>()
            {
                new Products()
                {
                    ProductId = "1",
                    ProductName = "External Hard Disks"
                },
                new Products()
                {
                    ProductId = "2",
                    ProductName = "Pendrives"
                },
                new Products()
                {
                    ProductId = "3",
                    ProductName = "Mouse"
                },
                new Products()
                {
                    ProductId = "4",
                    ProductName = "Laptop Bags"
                },
                new Products()
                {
                    ProductId = "5",
                    ProductName = "Laptop Skins & Decals"
                }
            };
            return listofproducts;
        }
    }
}

After Implementing IProducts interface next we are going Register Service as Transient in ConfigureServices method.

Registering Service as Transient in ConfigureServices method

In ConfigureServices method of Startup class, we are registering IProducts interface with the concrete type ProductsConcrete in IOC container, and while registering we are going to set the lifetime of service as Transient.

Transient services create a new instance on each time you request.

AddTransient<TService, TImplementation>

We are going to pass IProducts interface as Service and ProductsConcrete as Implementation as shown below.

services.AddTransient<IProducts, ProductsConcrete>();

Code Snippet

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DemoTypesofDependencyInjection.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace DemoTypesofDependencyInjection
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<IProducts, ProductsConcrete>();
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

After Registering Service Next, we are going to Add Controller with Name ‘DemoController‘.

Adding Controller and Index Action Method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace DemoTypesofDependencyInjection.Controllers
{
    public class DemoController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

After we have Registered Service and Created Controller Next, we are going to implement different types of injection let’s begin with constructor injection. 

Constructor Injection

In Constructor Injection, the dependency is injected through the constructor of a class. We have a Demo controller where we are going to implement Constructor Injection.

Here we are going to inject dependency from Constructor for that we have created parameterized constructor with IProduct interface as the parameter this will be resolved by the container at runtime.

Code Snippet

using DemoTypesofDependencyInjection.Repository;
using Microsoft.AspNetCore.Mvc;

namespace DemoTypesofDependencyInjection.Controllers
{
    public class DemoController : Controller
    {
        private readonly IProducts _products;
        public DemoController(IProducts products)
        {
            _products = products;
        }
        public IActionResult Index()
        {
            var listofproduts = _products.ListofProducts();
            return View();
        }
    }
}

For Method Injection, we have added a new Controller with Name Demo2Controller with Index Action Method in it.

Method Injection (FromServices attribute)

In Method Injection the dependency is injected directly to Action Method using FormService Attribute.

In Method injection, we can directly inject dependency in the Controller Action method just be decorating method with [FromServices] attribute and then passing Service (IProduct).

In Case you don’t need a service for more than one action within your controller at that time we can Use Method Injection.

Code Snippet of Demo2 Controller

using DemoTypesofDependencyInjection.Repository;
using Microsoft.AspNetCore.Mvc;

namespace DemoTypesofDependencyInjection.Controllers
{
    public class Demo2Controller : Controller
    {
        public IActionResult Index([FromServices] IProducts products)
        {
            var listofproduts = products.ListofProducts();
            return View();
        }
    }
} 

For Injecting Dependency into Razor View, we have added a new Controller with Name Demo3Controller with Index Action Method and View.

Injecting Dependency into Razor Views (@inject directive)

If you want to inject Service into View Directly it can be injected using the @inject directive.

In below View, you can see we have Used @inject directive to inject Product Dependency and then we have access ListofProducts and using foreach loop we have displayed each product on View.

Code Snippet of Index.cshtml

@using DemoTypesofDependencyInjection.Repository
@{
    Layout = null;
}
@inject IProducts Products
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <table border="1">
        <tr>
            <th>ProductId</th>
            <th>ProductName</th>
        </tr>

        @foreach (var product in Products.ListofProducts())
        {
            <tr>
                <td>@product.ProductId</td>
                <td>@product.ProductName</td>
            </tr>
        }

    </table>
</body>
</html>

Output

By Saineshwar Bageri

I am Microsoft MVP | C# Corner MVP | Code Project MVP | FULL STACK .NET Developer and working on .Net Web Technology (Asp.net, Asp.net Core,.Net Core, C#, Sqlserver, MVC, Windows, Console Application, javascript, jquery, json, ORM Dapper) and also a freelance developer.