-
Notifications
You must be signed in to change notification settings - Fork 9
Queries
João Simões edited this page Aug 19, 2017
·
2 revisions
To be able to read data, this library has support for queries that are fetched into a single and required query handler using generic variance.
The following interfaces and abstract classes are used to implement the query pattern:
Interface/Class | Description |
---|---|
IQuery<TResult> |
interface that represents a query that will have an operation result |
Query<TResult> |
abstract class that implements the IQuery<TResult> interface |
IQueryHandler<TQuery,TResult> |
interface that will handle asynchronously a TQuery instance extending from IQuery<TResult> and fetching the query data |
QueryHandlerNotFoundException |
exception thrown if no handler is found by the mediator when fetching a query |
The following properties are included in the query interfaces:
Property | Description |
---|---|
Id |
required unique identifier for each query. It may be used to detect query duplication, allowing to fetch the data from a cache or just for logging purposes. The abstract query classes will assign a Guid.NewGuid() value |
CreatedOn |
required date and time in which the query was created. The abstract query classes will assign a DateTimeOffset.Now value |
CreatedBy |
a string identifier for the user who created the query |
To create a query just implement the IQuery<TResult>
interface or corresponding abstract class:
public class UserByIdQuery<User> : Query<User>, IQuery<User> {
public Guid UserId { get; set; }
}
public class User {
public string Email { get; set; }
}
To handle a query just implement the IQueryHandler<TQuery,TResult>
interface:
public class UserQueryHandler : IQueryHandler<UserByIdQuery,User> {
public async Task<User> HandleAsync(UserByIdQuery query, CancellationToken ct) {
User user = null;
// try to get the user from the store
return user;
}
}
To fetch the data from a query, you only need the mediator instance and use the FetchAsync
method:
var user = await _mediator.FetchAsync<UserByIdQuery,User>(new UserByIdQuery {
UserId = Guid.Parse("6ca84be0-d509-4263-9e06-f255ecb4144c")
}, ct);