ASP.NET Core Dependency Injection Simple Example

Create an ASP.NET Core MVC Web Application and inside Models folder create the following Product class.

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Create the folder Services and add an interface IProductService with a single GetProducts method.

public interface IProductService
{
    List<Product> GetProducts();
}

Next, create a class with the name AmazonProductService and Implement IProductService interface on this class. For this tutorial, I am not using any backend repository or service to load products from the database so to keep things simple, Let’s just return some hard-coded products from the GetProducts method as follows:

public class AmazonProductService : IProductService
{
    public List<Product> GetProducts()
    {
        return new List<Product>()
        {
            new Product() { Id = 1001, Name = "Apple AirPods Pro", Price = 249.00m },
            new Product() { Id = 1002, Name = "Sony Noise Cancelling Headphones", Price = 199.00m },
            new Product() { Id = 1003, Name = "Acer Aspire 5 Slim Laptop", Price = 346.00m } 
        };
    }
}

Next, we need to register our service in Startup class as follows:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    { 
        services.AddTransient<IProductService, AmazonProductService>(); 
    }
}

Next, we need to inject our service into the controller. We can inject services inside the constructor of the controller as shown below:

public class HomeController : Controller
{
    private readonly IProductService _productService;
    public HomeController(IProductService productService)
    {
        _productService = productService;
    }
    public IActionResult Index()
    {
        var products = _productService.GetProducts();
        return View(products);
    }
}

Finally, we can display products in our Index.cshtml razor view file as follows:

@model List<Product>
@{
    ViewData["Title"] = "Home Page";
}
<br />
<br />
<div>
    <h3 class="text-center">ASP.NET Core Dependency Injection</h3>
    <br />
    <table class="table">
        <thead class="thead-dark">
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var product in Model)
            {
                <tr>
                    <td>@product.Id</td>
                    <td>@product.Name</td>
                    <td>@product.Price</td>
                </tr>
            }
        </tbody>
    </table>
</div>

Run the application and you should be able to see all the products returned from AmazonProductService. This is because at runtime when our Home Controller has requested the instance of the class implementing IProductService, the dependency injection framework resolved it to the AmazonProductService registered in Startup.cs class.

Let’s say your application requirements change and you suddenly decided that the products should load from Ebay instead of Amazon. You can create another class EbayProductService that is implementing the same IProductService interface and has its own implementation of GetProducts method.

public class EbayProductService : IProductService
{
    public List<Product> GetProducts()
    {
        return new List<Product>()
        {
            new Product() { Id = 2001, Name = "Apple iPhone XS Max", Price = 660.00m },
            new Product() { Id = 2002, Name = "Apple iPhone 7", Price = 134.00m },
            new Product() { Id = 2003, Name = "Sony Cyber Shot Camera", Price = 109.00m }
        };
    }
}

You don’t have to change a single line of code in your application. You just have to register EbayProductService in Startup.cs file and you are done.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    { 
        services.AddTransient<IProductService, EbayProductService>(); 
    }
}

Controllers and Views that have a dependency on IProductService will automatically start displaying Ebay Products instead of Amazon products.

Dynamically Register Services in DI Container

Let’s say you are in a situation where you want to use two different services based on the environment. You want to test Amazon service when you are in the development environment but you want to use Ebay service in the production environment. You can easily achieve this by injecting the IWebHostEnvironment inside the constructor of Startup class and then you can register services dynamically as shown below.

public class Startup
{
    private IWebHostEnvironment _env;
 
    public Startup(IWebHostEnvironment env)
    {
        _env = env;
    }
 
    public void ConfigureServices(IServiceCollection services)
    {
        if (_env.IsProduction())
        {
            services.AddTransient<IProductService, EbayProductService>();
        }
        else
        {
            services.AddTransient<IProductService, AmazonProductService>();
        } 
    }
}

Reference

This article has good explanation of dependency injection in general.

Step by Step guide to ASP.NET Core dependency injection

How To Update Raspberry Pi

Start by updating the list of repository packages:

sudo apt update

When this is done, run the update command:

sudo apt dist-upgrade

Follow any instructions and wait for the Pi update. When you’re done, type in:

sudo apt clean

This will delete unnecessary files that were uploaded during the update. Finish by restarting:

sudo reboot

When your Raspberry Pi is restarted, you will use the latest version of Raspbian.

For more info, read here

Hosting application targeting multiple framework

If the application is targeting multiple frameworks e.g. NET Core 2.1 and .NET Framework 4.6.1, you will need to install Hosting Bundle for it. Here is how;

https://dotnet.microsoft.com/en-us/download/dotnet/2.1

Restart your IIS box.

Make sure App poll is using v4.0 of .NET CLR version.

This will also help to solve this error;

IIS: Handler “aspNetCore” has a bad module “AspNetCoreModuleV2” in its module list

Version of .Net Framework, IIS App Pool is using?

.Net Framework 4.5 was installed on my machine and on the IIS Application Pool, I set the .NET CLR version to 4.0.

The AppPool’s .NET CLR Version is different from the .NET Framework Version.

The AppPool’s .NET CLR Version is different from the .NET Framework Version.

The .NET CLR Version 4.0 is the CLR base for the following .NET Framework Versions:

  • 4
  • 4.5 (including 4.5.1 and 4.5.2)
  • 4.6 (including 4.6.1 and 4.6.2 Preview)

So having a .NET CLR Version of 4.0 just means you support the above Frameworks, which will run under their deployed framework version.

Source: https://learn.microsoft.com/en-us/dotnet/standard/clr#clr-versions

Here is a full mapping of CLR to .NET Framework versions, based off this official documentation. https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies#version-information

CLR 1.0

.NET Framework 1.0


CLR 1.1

.NET Framework 1.1


CLR 2.0

.NET Framework 2.0

.NET Framework 3.0

.NET Framework 3.5


CLR 4

.NET Framework 4

.NET Framework 4.5

.NET Framework 4.5.1

.NET Framework 4.5.2

.NET Framework 4.6

.NET Framework 4.6.1

.NET Framework 4.6.2

.NET Framework 4.7

.NET Framework 4.7.1

.NET Framework 4.7.2

.NET Framework 4.8

Reference

https://stackoverflow.com/questions/37952860/which-version-of-the-net-framework-is-iis-using-for-my-apppool

What are progressive web apps? Best Progressive Web App list

Think of a responsive website and add native app functionalities to it. They’re developed with lightweight web technologies of HTML, CSS, and JavaScript as speed is essential for conversions.

In 2022, internet traffic is split 38.6/59% between desktop and mobile. As 76% of customers expect a comparable product experience across channels, companies turn towards progressive web apps (PWAs) — advanced websites that provide app-like functionalities on mobile devices. 

Read more here

https://www.monterail.com/blog/pwa-examples

To get started, here are the links;

https://learn.microsoft.com/en-us/microsoft-edge/progressive-web-apps-chromium/how-to/