پیاده سازی CQRS توسط MediatR - قسمت پنجم
نویسنده: معین تاجیک
تاریخ: ۱۳۹۷/۱۲/۰۵ ۲:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
کدهای این قسمت بهروزرسانی شده و از این ریپازیتوری قابل دسترسی است.
docker run --name eventstore-node -d -p 2113:2113 -p 1113:1113 eventstore/eventstore
Install-Package EventStore.Client
public class EventStoreDbContext : IEventStoreDbContext
{
public async Task<IEventStoreConnection> GetConnection()
{
IEventStoreConnection connection = EventStoreConnection.Create(
new IPEndPoint(IPAddress.Loopback, 1113),
nameof(MediatrTutorial));
await connection.ConnectAsync();
return connection;
}
public async Task AppendToStreamAsync(params EventData[] events)
{
const string appName = nameof(MediatrTutorial);
IEventStoreConnection connection = await GetConnection();
await connection.AppendToStreamAsync(appName, ExpectedVersion.Any, events);
}
} services.AddSingleton<IEventStoreDbContext, EventStoreDbContext>();
public class EventLoggerBehavior<TRequest, TResponse> :
IPipelineBehavior<TRequest, TResponse>
{
readonly IEventStoreDbContext _eventStoreDbContext;
public EventLoggerBehavior(IEventStoreDbContext eventStoreDbContext)
{
_eventStoreDbContext = eventStoreDbContext;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
TResponse response = await next();
string requestName = request.ToString();
// Commands convention
if (requestName.EndsWith("Command"))
{
Type requestType = request.GetType();
string commandName = requestType.Name;
var data = new Dictionary<string, object>
{
{
"request", request
},
{
"response", response
}
};
string jsonData = JsonConvert.SerializeObject(data);
byte[] dataBytes = Encoding.UTF8.GetBytes(jsonData);
EventData eventData = new EventData(eventId: Guid.NewGuid(),
type: commandName,
isJson: true,
data: dataBytes,
metadata: null);
await _eventStoreDbContext.AppendToStreamAsync(eventData);
}
return response;
}
} services.AddScoped(typeof(IPipelineBehavior<,>), typeof(EventLoggerBehavior<,>));