Using appsettings.json in Asp.net core 6 Program.cs file

In case that we have in appsettings;

"settings": {
    "url": "myurl",
    "username": "guest",
    "password": "guest"
  }

and we have the class;

public class Settings
    {
        public string Url { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }

we can use also;

var settings = builder.Configuration.GetSection("Settings").Get<Settings>();

var url = settings.Url;

Reference

https://stackoverflow.com/questions/69390676/how-to-use-appsettings-json-in-asp-net-core-6-program-cs-file

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

JSON Circular Reference Loop Error running Raw SQL in Web API using EF Core

I had a complex stored procedure that I needed to run using EF core in a Web API project. I cannot use LINQ to represent this query. I have followed all best practices outlined here;

Everything worked great except raw sql endpoint. It started giving me “Circular Reference loop error”. To keep thing simple, I am returning DTO from endpoint not the entity.

Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'task' with type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Collections.Generic.IEnumerable`1[FM.Service.Shared.DTO.TranMasterViewDto],FM.Service.LedgerTranViewService+<GetTransactionForProjectActionAsync>d__4]'. Path 'stateMachine.<>t__builder'
......

Here is my configuration before and after the fix;

Newtonsoft Configuration in program.cs file before the fix;
}).AddNewtonsoftJson()
Newtonsoft Configuration in program.cs file after the fix;
}).AddNewtonsoftJson(
    options => 
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)

The error is gone and I am getting this results.

{
    "stateMachine": {
        "<>1__state": 0,
        "<>t__builder": {},
        "projectActionID": "82ee5154-971a-ed11-90e6-00155d717606",
        "trackChanges": false,
        "<>4__this": {}
    },
    "context": {},
    "moveNextAction": {
        "method": {
            "name": "MoveNext",

Wait…This is not what I expected. Why I am getting Tasks result where I need to see my Dto results.

It turns out that I am not returning results from my Async method but the task;

public async Task<IActionResult> GetTransactionForProjectActionAsync(Guid projectActionId)
{
   return Ok(_service.LedgerTranViewService.GetTransactionForProjectActionAsync(projectActionId, trackChanges: false));
        }

Fixing the return type has solved all of my problems;

return Ok(_service.LedgerTranViewService.GetTransactionForProjectActionAsync(projectActionId, trackChanges: false).Result);
        }
[
    {
        "id": 20221,
        "projectActionID": "82ee5154-971a-ed11-90e6-00155d717606",        
        "tranMasterDetail": [
            {
                "tranMasterId": "9358b0c5-6d30-ed11-90e8-00155d717606",
                "ledgerID": "63302216-0946-ea11-ac82-f81654967f7a",
                "tranDescription": "Rent paid",
                "tranDate": "2022-01-03T00:00:00",
                "tranFlag": 0,
                "tranAmount": 1300.00
            }
        ]
    }
]

Remove Newtonsoft ReferenceLoopHandler from program.cs file.

}).AddNewtonsoftJson()

Hope this will help someone.

Reference

https://stackoverflow.com/questions/62985907/avoid-or-control-circular-references-in-entity-framework-core