添加serilog日志支持和部分其他efcore代码

This commit is contained in:
2021-02-23 16:16:03 +08:00
parent 0f98c15cd4
commit d639db3574
19 changed files with 506 additions and 28 deletions

2
.gitignore vendored
View File

@@ -1,3 +1,5 @@
.vs/
bin/
obj/
/QRCodeService/Logs
.user

View File

@@ -7,9 +7,8 @@ using System.Threading.Tasks;
namespace Domain.AggregateModel.AppAggregate
{
public class App : IAggregateRoot
public class App :Entity, IAggregateRoot
{
public int Id { get; private set; }
public string AppKey { get;private set; }
public string BaseUrl { get; private set; }
public string Remarks { get;private set; }

View File

@@ -10,7 +10,7 @@ using System.Threading.Tasks;
namespace Domain.AggregateModel.LinkAggregate
{
public class Link:IAggregateRoot
public class Link:Entity,IAggregateRoot
{
/// <summary>
/// 非自增主键

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>

View 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));
}
}
}
}

View File

@@ -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();
}
}
}

View File

@@ -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();
}
}
}

View File

@@ -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>

View 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);
}
}
}

View File

@@ -0,0 +1,24 @@
using MediatR;
using Microsoft.Extensions.Logging;
using QRCodeService.Extensions;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace QRCodeService.Application.Behaviors
{
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger) => _logger = logger;
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
_logger.LogInformation("----- Handling command {CommandName} ({@Command})", request.GetGenericTypeName(), request);
var response = await next();
_logger.LogInformation("----- Command {CommandName} handled - response: {@Response}", request.GetGenericTypeName(), response);
return response;
}
}
}

View File

@@ -0,0 +1,73 @@
using Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using QRCodeService.Extensions;
using Serilog.Context;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace QRCodeService.Application.Behaviors
{
public class TransactionBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly ILogger<TransactionBehaviour<TRequest, TResponse>> _logger;
private readonly AppDbContext _dbContext;
//private readonly IOrderingIntegrationEventService _orderingIntegrationEventService;
public TransactionBehaviour(AppDbContext dbContext,
//IOrderingIntegrationEventService orderingIntegrationEventService,
ILogger<TransactionBehaviour<TRequest, TResponse>> logger)
{
_dbContext = dbContext ?? throw new ArgumentException(nameof(AppDbContext));
//_orderingIntegrationEventService = orderingIntegrationEventService ?? throw new ArgumentException(nameof(orderingIntegrationEventService));
_logger = logger ?? throw new ArgumentException(nameof(ILogger));
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
var response = default(TResponse);
var typeName = request.GetGenericTypeName();
try
{
if (_dbContext.HasActiveTransaction)
{
return await next();
}
var strategy = _dbContext.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
Guid transactionId;
using (var transaction = await _dbContext.BeginTransactionAsync())
using (LogContext.PushProperty("TransactionContext", transaction.TransactionId))
{
_logger.LogInformation("----- Begin transaction {TransactionId} for {CommandName} ({@Command})", transaction.TransactionId, typeName, request);
response = await next();
_logger.LogInformation("----- Commit transaction {TransactionId} for {CommandName}", transaction.TransactionId, typeName);
await _dbContext.CommitTransactionAsync(transaction);
transactionId = transaction.TransactionId;
}
//await _orderingIntegrationEventService.PublishEventsThroughEventBusAsync(transactionId);
});
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "ERROR Handling transaction for {CommandName} ({@Command})", typeName, request);
throw;
}
}
}
}

View File

@@ -0,0 +1,45 @@
using FluentValidation;
using MediatR;
using Microsoft.Extensions.Logging;
using QRCodeService.Extensions;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace QRCodeService.Application.Behaviors
{
public class ValidatorBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly ILogger<ValidatorBehavior<TRequest, TResponse>> _logger;
private readonly IValidator<TRequest>[] _validators;
public ValidatorBehavior(IValidator<TRequest>[] validators, ILogger<ValidatorBehavior<TRequest, TResponse>> logger)
{
_validators = validators;
_logger = logger;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
var typeName = request.GetGenericTypeName();
_logger.LogInformation("----- Validating command {CommandType}", typeName);
var failures = _validators
.Select(v => v.Validate(request))
.SelectMany(result => result.Errors)
.Where(error => error != null)
.ToList();
if (failures.Any())
{
_logger.LogWarning("Validation errors - {CommandType} - Command: {@Command} - Errors: {@ValidationErrors}", typeName, request, failures);
//throw new OrderingDomainException(
// $"Command Validation Errors for type {typeof(TRequest).Name}", new ValidationException("Validation exception", failures));
}
return await next();
}
}
}

View File

@@ -6,14 +6,22 @@ using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace QRCodeService.Controllers
{
[Route("[controller]/[action]")]
public class PlaygroundController:ControllerBase
{
private readonly ILogger<PlaygroundController> logger;
public PlaygroundController(ILogger<PlaygroundController> logger)
{
this.logger = logger;
}
public IActionResult GenShortCode(string url)
{
logger.LogInformation("duduledule");
var codes = new string[2];
using (var md5 = MD5.Create())
{

View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QRCodeService.Extensions
{
public static class GenericTypeExtensions
{
public static string GetGenericTypeName(this Type type)
{
var typeName = string.Empty;
if (type.IsGenericType)
{
var genericTypes = string.Join(",", type.GetGenericArguments().Select(t => t.Name).ToArray());
typeName = $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>";
}
else
{
typeName = type.Name;
}
return typeName;
}
public static string GetGenericTypeName(this object @object)
{
return @object.GetType().GetGenericTypeName();
}
}
}

View File

@@ -1,26 +1,36 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
namespace QRCodeService
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IConfiguration Configuration { get; } = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddJsonFile($"appsettings.{Environment.MachineName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.CreateLogger();
CreateHostBuilder(args).Build().Run();
}
}
}
}

View File

@@ -13,10 +13,18 @@
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.1" NoWarn="NU1605" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.1" NoWarn="NU1605" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.3" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.9" />
<PackageReference Include="MySqlConnector" Version="1.2.0" />
<PackageReference Include="MySqlConnector" Version="1.2.1" />
<PackageReference Include="QRCoder" Version="1.4.1" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.Async" Version="1.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="5.0.0-alpha.2" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="5.0.0" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup>
<ActiveDebugProfile>Docker</ActiveDebugProfile>
<Controller_SelectedScaffolderID>ApiControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath>
</PropertyGroup>
</Project>

View File

@@ -1,14 +1,21 @@
using Infrastructure;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Pomelo.EntityFrameworkCore.MySql;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using QRCodeService.Application.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace QRCodeService
@@ -31,6 +38,25 @@ namespace QRCodeService
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "QRCodeService", Version = "v1" });
});
//MediatR
services.AddMediatR(Assembly.GetExecutingAssembly());
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(TransactionBehaviour<,>));
//EFCore
services.AddDbContextPool<AppDbContext>(
dbContextOptions => dbContextOptions
.UseMySql(
"server=localhost;user=root;password=root;database=qrcode",
// For common usages, see pull request #1233.
new MariaDbServerVersion(new Version(10, 5, 9)), // use MariaDbServerVersion for MariaDB
mySqlOptions => mySqlOptions
.CharSetBehavior(CharSetBehavior.NeverAppend))
// Everything from this point on is optional but helps with debugging.
.EnableSensitiveDataLogging()
.EnableDetailedErrors()
);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

View File

@@ -6,5 +6,38 @@
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"Serilog": {
"Using": [ "SeriLog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Async" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "File",
"Args": {
"path": "Logs/log.txt",
"rollingInterval": "Day"
}
}
]
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "SerilogExample"
}
}
}