添加serilog日志支持和部分其他efcore代码
This commit is contained in:
145
Infrastructure/AppDbContext.cs
Normal file
145
Infrastructure/AppDbContext.cs
Normal file
@@ -0,0 +1,145 @@
|
||||
using Domain.AggregateModel.AppAggregate;
|
||||
using Domain.AggregateModel.LinkAggregate;
|
||||
using Domain.SeedWork;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Infrastructure
|
||||
{
|
||||
public class AppDbContext : DbContext, IUnitOfWork
|
||||
{
|
||||
public DbSet<App> Apps { get; set; }
|
||||
public DbSet<Link> Links { get; set; }
|
||||
|
||||
private readonly IMediator _mediator;
|
||||
private IDbContextTransaction _currentTransaction;
|
||||
public bool HasActiveTransaction => _currentTransaction != null;
|
||||
public IDbContextTransaction GetCurrentTransaction() => _currentTransaction;
|
||||
|
||||
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
|
||||
public AppDbContext(DbContextOptions<AppDbContext> options, IMediator mediator) : base(options)
|
||||
{
|
||||
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
|
||||
System.Diagnostics.Debug.WriteLine("OrderingContext::ctor ->" + this.GetHashCode());
|
||||
}
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
//modelBuilder.ApplyConfiguration(new ClientRequestEntityTypeConfiguration());
|
||||
//modelBuilder.ApplyConfiguration(new PaymentMethodEntityTypeConfiguration());
|
||||
//modelBuilder.ApplyConfiguration(new OrderEntityTypeConfiguration());
|
||||
//modelBuilder.ApplyConfiguration(new OrderItemEntityTypeConfiguration());
|
||||
//modelBuilder.ApplyConfiguration(new CardTypeEntityTypeConfiguration());
|
||||
//modelBuilder.ApplyConfiguration(new OrderStatusEntityTypeConfiguration());
|
||||
//modelBuilder.ApplyConfiguration(new BuyerEntityTypeConfiguration());
|
||||
}
|
||||
|
||||
|
||||
public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
// Dispatch Domain Events collection.
|
||||
// Choices:
|
||||
// A) Right BEFORE committing data (EF SaveChanges) into the DB will make a single transaction including
|
||||
// side effects from the domain event handlers which are using the same DbContext with "InstancePerLifetimeScope" or "scoped" lifetime
|
||||
// B) Right AFTER committing data (EF SaveChanges) into the DB will make multiple transactions.
|
||||
// You will need to handle eventual consistency and compensatory actions in case of failures in any of the Handlers.
|
||||
await _mediator.DispatchDomainEventsAsync(this);
|
||||
|
||||
// After executing this line all the changes (from the Command Handler and Domain Event Handlers)
|
||||
// performed through the DbContext will be committed
|
||||
var result = await base.SaveChangesAsync(cancellationToken);
|
||||
return true;
|
||||
}
|
||||
public async Task<IDbContextTransaction> BeginTransactionAsync()
|
||||
{
|
||||
if (_currentTransaction != null) return null;
|
||||
|
||||
_currentTransaction = await Database.BeginTransactionAsync(IsolationLevel.ReadCommitted);
|
||||
|
||||
return _currentTransaction;
|
||||
}
|
||||
|
||||
public async Task CommitTransactionAsync(IDbContextTransaction transaction)
|
||||
{
|
||||
if (transaction == null) throw new ArgumentNullException(nameof(transaction));
|
||||
if (transaction != _currentTransaction) throw new InvalidOperationException($"Transaction {transaction.TransactionId} is not current");
|
||||
|
||||
try
|
||||
{
|
||||
await SaveChangesAsync();
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
RollbackTransaction();
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (_currentTransaction != null)
|
||||
{
|
||||
_currentTransaction.Dispose();
|
||||
_currentTransaction = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void RollbackTransaction()
|
||||
{
|
||||
try
|
||||
{
|
||||
_currentTransaction?.Rollback();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (_currentTransaction != null)
|
||||
{
|
||||
_currentTransaction.Dispose();
|
||||
_currentTransaction = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public class AppDbContextDesignFactory : IDesignTimeDbContextFactory<AppDbContext>
|
||||
{
|
||||
public AppDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseMySql("Server=localhost;Database=qrcode;Uid=root;Pwd=root;");
|
||||
|
||||
return new AppDbContext(optionsBuilder.Options, new NoMediator());
|
||||
}
|
||||
|
||||
class NoMediator : IMediator
|
||||
{
|
||||
public Task Publish<TNotification>(TNotification notification, CancellationToken cancellationToken = default(CancellationToken)) where TNotification : INotification
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task Publish(object notification, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<TResponse> Send<TResponse>(IRequest<TResponse> request, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
return Task.FromResult(default(TResponse));
|
||||
}
|
||||
|
||||
public Task<object> Send(object request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return Task.FromResult(default(object));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Domain.AggregateModel.AppAggregate;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Infrastructure.EntityConfigurations
|
||||
{
|
||||
public class AppEntityTypeConfiguration : IEntityTypeConfiguration<App>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<App> builder)
|
||||
{
|
||||
builder.ToTable("App");
|
||||
builder.HasKey(a => a.Id);
|
||||
builder.Ignore(a => a.DomainEvents);
|
||||
builder.Property(a => a.Id)
|
||||
.ValueGeneratedOnAdd()
|
||||
.IsRequired();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Domain.AggregateModel.LinkAggregate;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Infrastructure.EntityConfigurations
|
||||
{
|
||||
public class LinkEntityTypeConfiguration : IEntityTypeConfiguration<Link>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Link> builder)
|
||||
{
|
||||
builder.ToTable("Link");
|
||||
builder.HasKey(l => l.ShortCode);
|
||||
builder.Ignore(l => l.DomainEvents);
|
||||
builder.Property(l => l.AppId).IsRequired();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.3">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.3" />
|
||||
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.2.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Domain\Domain.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
27
Infrastructure/MediatorExtension.cs
Normal file
27
Infrastructure/MediatorExtension.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
using Domain.SeedWork;
|
||||
using MediatR;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Infrastructure
|
||||
{
|
||||
static class MediatorExtension
|
||||
{
|
||||
public static async Task DispatchDomainEventsAsync(this IMediator mediator, AppDbContext ctx)
|
||||
{
|
||||
var domainEntities = ctx.ChangeTracker
|
||||
.Entries<Entity>()
|
||||
.Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any());
|
||||
|
||||
var domainEvents = domainEntities
|
||||
.SelectMany(x => x.Entity.DomainEvents)
|
||||
.ToList();
|
||||
|
||||
domainEntities.ToList()
|
||||
.ForEach(entity => entity.Entity.ClearDomainEvents());
|
||||
|
||||
foreach (var domainEvent in domainEvents)
|
||||
await mediator.Publish(domainEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user