55 lines
2.2 KiB
C#
Raw Normal View History

2017-03-24 12:37:44 +01:00
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
2017-03-24 12:37:44 +01:00
using System;
using Microsoft.EntityFrameworkCore.Diagnostics;
2017-03-24 12:37:44 +01:00
namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services
{
public class IntegrationEventLogService : IIntegrationEventLogService
{
private readonly IntegrationEventLogContext _integrationEventLogContext;
2017-03-24 12:37:44 +01:00
private readonly DbConnection _dbConnection;
2017-03-24 12:37:44 +01:00
public IntegrationEventLogService(DbConnection dbConnection)
{
2017-03-24 12:37:44 +01:00
_dbConnection = dbConnection?? throw new ArgumentNullException("dbConnection");
_integrationEventLogContext = new IntegrationEventLogContext(
new DbContextOptionsBuilder<IntegrationEventLogContext>()
2017-03-24 12:37:44 +01:00
.UseSqlServer(_dbConnection)
.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning))
.Options);
}
2017-03-24 12:37:44 +01:00
public Task SaveEventAsync(IntegrationEvent @event, DbTransaction transaction)
{
2017-03-24 12:37:44 +01:00
if(transaction == null)
{
throw new ArgumentNullException("transaction", $"A {typeof(DbTransaction).FullName} is required as a pre-requisite to save the event.");
}
var eventLogEntry = new IntegrationEventLogEntry(@event);
2017-03-24 12:37:44 +01:00
_integrationEventLogContext.Database.UseTransaction(transaction);
_integrationEventLogContext.IntegrationEventLogs.Add(eventLogEntry);
return _integrationEventLogContext.SaveChangesAsync();
}
public Task MarkEventAsPublishedAsync(IntegrationEvent @event)
{
var eventLogEntry = _integrationEventLogContext.IntegrationEventLogs.Single(ie => ie.EventId == @event.Id);
eventLogEntry.TimesSent++;
eventLogEntry.State = EventStateEnum.Published;
_integrationEventLogContext.IntegrationEventLogs.Update(eventLogEntry);
return _integrationEventLogContext.SaveChangesAsync();
}
}
}