http error 500.0 – ancm in-process handler load failure


Hi All

Today I was running Identity Server 4 asp.net core application on my system. I was getting below exception.

http error 500.0 – ancm in-process handler load failure

I fixed the issue like given below

>> Change the hosting model to out of process

How to call token based web api in Blazor


Here is the syntax for calling taken based web api in Blazor server or webassembly.

using MyFleetApp.Data.Model;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;


namespace MyFleetApp.Data.Service
{
    public class InvoiceSearchService : IInvoiceSerach
    {
        private readonly HttpClient httpClient;
        public InvoiceSearchService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }
       

        public async Task<Rootobject> GetInvoices(Rootobject objParameter)
        {
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", objParameter.token);
            var result = await httpClient.PostAsJsonAsync<Rootobject>("Web API URL will be here", objParameter);
            Rootobject objInvoice = new Rootobject();
            if (result.IsSuccessStatusCode)
            {
                objInvoice = await result.Content.ReadFromJsonAsync<Rootobject>();
            }

            return objInvoice;
        }
    }
}

CQRS with MediatR Pattern in Asp.net Core Web Api 5.0


What is the CQRS ?

CQRS is the Command Query Responsibility Segregation design pattern. In this pattern Command is used to Insert/Update/Delete operation . Query is used to fetching data from database.

What are advantages of CQRS Pattern ?

  1. Highly scalable : while creating microservice api, we can easily scale up our application, if we we have written the code for command and query in separate layer.
  2. Improved Performance : If we have segregated the read and write functionalities separate layer and deployed as separately then it will give very good performance.

What is the MediatR Pattern ?

Mediator is a behavioral design pattern that lets you reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object. It supports easy maintenance of the code by loose coupling. Mediator pattern falls under behavioral pattern category.

How to implement in Asp.net core web api 5.0 ?

I m creating very simple application to understand this pattern, I m going to use VS 2019. We are going to achieve CQRS pattern using MediatR nuget package manager

Step 1: Create the Asp.net Web Api 5.0 application.

Step 2: Install the MediatR package like given below

Make sure to install Entity Framework related package

Step 3: Go to the start up file of ConfigureService and add the MediatR Service like this

Step 4: Go to the Model folder of Application and create the Emp Class like

Step 5: Create the Context folder in application and Create the IApplicationContext interface like this

using CQRS_Emp_Demo.Model;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo.Context
{
    public interface IApplicationContext
    {
        DbSet<Emp> Emps { get; set; }

        Task<int> SaveChangesAsync();
    }
}

Step 6: Create ApplicationContext class for Emp Model like this

using CQRS_Emp_Demo.Model;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo.Context
{
    public class ApplicationContext : DbContext, IApplicationContext
    {
        public DbSet<Emp> Emps { get; set; }
        public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
        {

        }
        public async Task<int> SaveChangesAsync()
        {
            return await base.SaveChangesAsync();
        }
    }
}

Step 7: Clean and rebuild the application then run this command

add-migration “initial”
update-database

Step 8: Create the Command and Query Folder as given below image

Step 9: In Queries folder create GetAllEmpsQuery class and write the code like this

using CQRS_Emp_Demo.Context;
using CQRS_Emp_Demo.Model;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo
{
    public class GetAllEmpsQuery : IRequest<IEnumerable<Emp>>
    {
        public class GetAllEmpsQueryHandler : IRequestHandler<GetAllEmpsQuery, IEnumerable<Emp>>
        {
            private readonly IApplicationContext _context;
            public GetAllEmpsQueryHandler(IApplicationContext context)
            {
                _context = context;
            }
            public async Task<IEnumerable<Emp>> Handle(GetAllEmpsQuery request, CancellationToken cancellationToken)
            {
                var emplist = await _context.Emps.ToListAsync();
                if (emplist == null)
                {
                    return null;
                }
                return emplist.AsReadOnly();
            }
        }
    }
}

In the above code we are using IRequest and IRequestHandler interface of mediator library to make loose couple code.

Step 9: Create the Class i.e. GetEmpByIdQuery.cs and write the code like this

using CQRS_Emp_Demo.Context;
using CQRS_Emp_Demo.Model;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo
{
    public class GetEmpByIdQuery : IRequest<Emp>
    {
        public int Id { get; set; }
        public class GetEmpByIdQueryHandler : IRequestHandler<GetEmpByIdQuery, Emp>
        {
            private readonly IApplicationContext _context;
            public GetEmpByIdQueryHandler(IApplicationContext context)
            {
                _context = context;
            }

            public async Task<Emp> Handle(GetEmpByIdQuery request, CancellationToken cancellationToken)
            {
                var emp = await _context.Emps.Where(m => m.Id == request.Id).FirstOrDefaultAsync();
                if (emp == null) return null;
                return emp;
            }
        }
    }
}

Step 10: Now we will the code command service for Insert/Update/ Delete in Command folder like this

For CreateEmpCommand.cs

using CQRS_Emp_Demo.Context;
using CQRS_Emp_Demo.Model;
using MediatR;
using System.Threading;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo
{
    public class CreateEmpCommand : IRequest<int>
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
        public string Country { get; set; }

        public class CreateEmpCommandHandler : IRequestHandler<CreateEmpCommand, int>
        {
            private readonly IApplicationContext _context;
            public CreateEmpCommandHandler(IApplicationContext context)
            {
                _context = context;
            }
            public async Task<int> Handle(CreateEmpCommand request, CancellationToken cancellationToken)
            {
                var emp = new Emp();
                emp.EmpName = request.EmpName;
                emp.EmpAddress = request.EmpAddress;
                emp.Country = request.Country;
                _context.Emps.Add(emp);
                int flag = await _context.SaveChangesAsync();
                return flag;
            }
        }
    }
}

For UpdateCommand.cs

using CQRS_Emp_Demo.Context;
using MediatR;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo
{
    public class UpdateEmpCommand : IRequest<int>
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
        public string Country { get; set; }
        public class UpdateEmpCommandHandler : IRequestHandler<UpdateEmpCommand, int>
        {
            private readonly IApplicationContext _context;
            public UpdateEmpCommandHandler(IApplicationContext context)
            {
                _context = context;
            }
            public async Task<int> Handle(UpdateEmpCommand request, CancellationToken cancellationToken)
            {
                var emp = _context.Emps.Where(a => a.Id == request.Id).FirstOrDefault();
                if (emp == null)
                {
                    return default;
                }
                else
                {
                    emp.Country = request.Country;
                    emp.EmpAddress = request.EmpAddress;
                    emp.EmpName = request.EmpName;
                    int flag = await _context.SaveChangesAsync();
                    return flag;
                }
            }
        }
    }
}

For DeleteEmpCommand.cs

using CQRS_Emp_Demo.Context;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo
{
    public class DeleteEmpCommand : IRequest<int>
    {
        public int Id { get; set; }
        public class DeleteEmpCommandHandler : IRequestHandler<DeleteEmpCommand, int>
        {
            public readonly IApplicationContext _context;
            public DeleteEmpCommandHandler(IApplicationContext context)
            {
                _context = context;
            }

            public async Task<int> Handle(DeleteEmpCommand request, CancellationToken cancellationToken)
            {
                var emp = await _context.Emps.Where(m => m.Id == request.Id).FirstOrDefaultAsync();
                if (emp == null) return default;
                _context.Emps.Remove(emp);
                int flag = await _context.SaveChangesAsync();
                return flag;

            }
        }
    }
}

Step 11: Create the EmpController in Controller folder and write code like this

using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;


namespace CQRS_Emp_Demo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmpController : ControllerBase
    {
        private IMediator _mediator;
        protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();

        // GET: api/<EmpController>
        [HttpGet]
        public async Task<IActionResult> Get()
        {
            return Ok(await Mediator.Send(new GetAllEmpsQuery()));
        }

        // GET api/<EmpController>/5
        [HttpGet("{id}")]
        public async Task<IActionResult> GetEmpById(int id)
        {
            return Ok(await Mediator.Send(new GetEmpByIdQuery { Id = id }));
        }

        // POST api/<EmpController>
        [HttpPost]
        public async Task<IActionResult> SaveEmp(CreateEmpCommand command)
        {
            return Ok(await Mediator.Send(command));
        }

        // PUT api/<EmpController>/5
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateEmpById(int id, UpdateEmpCommand command)
        {
            if (id != command.Id)
            {
                return BadRequest();
            }
            return Ok(await Mediator.Send(command));
        }

        // DELETE api/<EmpController>/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            return Ok(await Mediator.Send(new DeleteEmpCommand { Id = id }));
        }
    }
}

Step 12: Rebuild and run the application then execute the get method in swagger, You will get output like this

Summary

In the above demo, we saw that how to implement CQRS using mediatR Nuget package manager in Asp.net Core web API 5.0 . I have implemented it in very simple database. If you want the source code then please download from below Github URL

https://github.com/Chandradev819/CQRS_Emp_Demo.git