Branch | Build status |
---|---|
master | |
develop |
Adds ability to create and process queries in the sense of CQRS.
dotnet add package Joint.CQRS.Queries
Implement IQuery<TResult>
interface in the selected class:
public class GetAccount : IQuery<AccountDto>
{
public Guid Id { get; set; }
}
Create dedicated query handler class that implements IQueryHandler<TQuery, TResult>
interface with HandleAsync()
method:
public class GetAccountHandler : IQueryHandler<GetAccount, AccountDto>
{
public Task<AccountDto> HandleAsync(GetAccount query)
{
//put the handling code here
}
}
You can easily register all query handlers in DI container by calling AddQueryHandlers()
method on IJointBuilder
:
public IServiceProvider ConfigureServices(this IServiceCollection services)
{
var builder = JointBuilder
.Create(services)
.AddQueryHandlers();
//other registrations
return builder.Build();
}
Dispatching a particular query object can be also done using Joint package. Start with registering in-memory dispatcher on your IJointBuilder
by calling a AddInMemoryEventDispatcher()
method:
public IServiceProvider ConfigureServices(this IServiceCollection services)
{
services.AddOpenTracing();
var builder = JointBuilder
.Create(services)
.AddQueryHandlers()
.AddInMemoryQueryDispatcher();
//other registrations
return builder.Build();
}
Then simply inject IQueryDispatcher
into a class and call QueryAsync()
method:
public class AccountsService
{
private readonly IQueryDispatcher _dispatcher;
public AccountsService(IQueryDispatcher dispatcher)
{
_dispatcher = dispatcher;
}
public Task<AccountDto> GetAccountAsync(Guid id)
=> _dispatcher.QueryAsync(new GetAccount { Id = id });
}