External Libraries -MANAGE HANDLERS in External Class Library for Micro services
Open Manage Nuget Packages
Install following Package here (To be used for Handler)
- mediatR
Create CQRS interface (in CQRS folder it self and these should be generic)
- ICommand.cs
using MediatR;
namespace MsExternalBlocks.CQRS;
// Unit is a representing weight type for the mediator
public interface ICommand : ICommand<Unit>{}
// Generics version allows for commands that produce a response.
public interface ICommand<out TResponse> : IRequest<TResponse>{}
- ICommandHandler.cs
using MediatR;
using static System.Runtime.InteropServices.JavaScript.JSType;namespace MsExternalBlocks.CQRS;
// In case there is no response, and do not return any response.
public interface ICommandHandler<in TCommand>
: ICommandHandler<TCommand, Unit>
where TCommand : ICommand<Unit>{ }
// Getting the response object And this response object should not be null.
public interface ICommandHandler<in TCommand, TResponse>
: IRequestHandler<TCommand, TResponse>
where TCommand : ICommand<TResponse>
where TResponse : notnull { }
- IQuery.cs
using MediatR;
namespace MsExternalBlocks.CQRS;
// Calling from other microservies
// This is used for the read operations.
public interface IQuery<out TResponse> : IRequest<TResponse>
where TResponse : notnull{}
- IQueryHandler.cs
using MediatR;
namespace MsExternalBlocks.CQRS;
// it specialized mediator.IRequest handler for handling the query request.
// A Public interface
public interface IQueryHandler<in TQuery, TResponse>
: IRequestHandler<TQuery, TResponse>
where TQuery : IQuery<TResponse>
where TResponse : notnull { }
You can see in here the query should be inherited from the query object.
But if you go to the command handler, this command should be comes from the ICommand. So that means we have separate query and command handler according to our abstraction.
Create Abstraction on MediatR for CQRS
We will create a clear separation between commands and queries using the mediator, enhancing the clarity and maintainability of our code.