diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Dcc/Masa.Contrib.BasicAbility.Dcc.csproj b/src/BasicAbility/Masa.Contrib.BasicAbility.Dcc/Masa.Contrib.BasicAbility.Dcc.csproj index 092aa02af..0a38ee85b 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Dcc/Masa.Contrib.BasicAbility.Dcc.csproj +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Dcc/Masa.Contrib.BasicAbility.Dcc.csproj @@ -7,9 +7,9 @@ - - - + + + diff --git a/src/Data/Masa.Contrib.Data.Contracts.EF/Masa.Contrib.Data.Contracts.EF.csproj b/src/Data/Masa.Contrib.Data.Contracts.EF/Masa.Contrib.Data.Contracts.EF.csproj index 19133b794..4678288b7 100644 --- a/src/Data/Masa.Contrib.Data.Contracts.EF/Masa.Contrib.Data.Contracts.EF.csproj +++ b/src/Data/Masa.Contrib.Data.Contracts.EF/Masa.Contrib.Data.Contracts.EF.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/Data/Masa.Contrib.Data.Contracts.EF/README.md b/src/Data/Masa.Contrib.Data.Contracts.EF/README.md index 23c0a1fe8..053f9760a 100644 --- a/src/Data/Masa.Contrib.Data.Contracts.EF/README.md +++ b/src/Data/Masa.Contrib.Data.Contracts.EF/README.md @@ -1,27 +1,3 @@ [中](README.zh-CN.md) | EN -## Contracts.EF - -Example: - -```C# -Install-Package Masa.Contrib.Data.UoW.EF -Install-Package Masa.Contrib.Data.Contracts.EF -``` - -```C# -builder.Services.AddEventBus(options => { - options.UseUoW(dbOptions => dbOptions.UseSoftDelete().UseSqlServer("server=localhost;uid=sa;pwd=P@ssw0rd;database=identity")); -}); -``` - -> When the entity inherits ISoftware and is deleted, change the delete state to the modified state, and cooperate with the custom Remove operation to achieve soft deletion -> Do not query the data marked as soft deleted when querying - -> Frequently Asked Questions: - -- Problem 1: After using UseSoftDelete, there is a problem that the submission cannot be saved - - After using Uow, the transaction will be enabled by default after Add、 Modified、 and Deleted - and the transaction can be saved normally after the transaction is submitted - If the EventBus is used, the transaction will be automatically submitted \ No newline at end of file +## Contracts.EF \ No newline at end of file diff --git a/src/Data/Masa.Contrib.Data.Contracts.EF/README.zh-CN.md b/src/Data/Masa.Contrib.Data.Contracts.EF/README.zh-CN.md index 20747fff0..2d2ba01b0 100644 --- a/src/Data/Masa.Contrib.Data.Contracts.EF/README.zh-CN.md +++ b/src/Data/Masa.Contrib.Data.Contracts.EF/README.zh-CN.md @@ -1,27 +1,3 @@ 中 | [EN](README.md) -## Contracts.EF - -用例: - -```C# -Install-Package Masa.Contrib.Data.UoW.EF -Install-Package Masa.Contrib.Data.Contracts.EF -``` - -```C# -builder.Services.AddEventBus(options => { - options.UseUoW(dbOptions => dbOptions.UseSoftDelete().UseSqlServer("server=localhost;uid=sa;pwd=P@ssw0rd;database=identity")); -}); -``` - -> 当实体继承ISoftware,且被删除时,将删除状态改为修改状态,并配合自定义Remove操作,实现软删除 -> 支持查询的时候不查询被标记软删除的数据 - -> 常见问题: - -- 问题1:使用UseSoftDelete后出现提交保存不上的问题 - - 使用Uow后,默认在进行Add、Modified、Deleted后会启用事务 - 需要提交事务之后才能正常保存 - 如果使用EventBus则会自动提交事务 \ No newline at end of file +## Contracts.EF \ No newline at end of file diff --git a/src/Data/Masa.Contrib.Data.Contracts.EF/ServiceCollectionExtensions.cs b/src/Data/Masa.Contrib.Data.Contracts.EF/ServiceCollectionExtensions.cs deleted file mode 100644 index 02448d8d8..000000000 --- a/src/Data/Masa.Contrib.Data.Contracts.EF/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace Masa.Contrib.Data.Contracts.EF; - -public static class ServiceCollectionExtensions -{ - [Obsolete("Please use optionsBuilder.UseSoftDelete()")] - public static MasaDbContextOptionsBuilder UseSoftDelete( - this MasaDbContextOptionsBuilder masaDbContextOptionsBuilder, - IServiceCollection services) => masaDbContextOptionsBuilder.UseSoftDelete(); - - public static MasaDbContextOptionsBuilder UseSoftDelete( - this MasaDbContextOptionsBuilder masaDbContextOptionsBuilder) - { - if (masaDbContextOptionsBuilder.Services.Any(s => s.ImplementationType == typeof(ContractsFilter))) return masaDbContextOptionsBuilder; - masaDbContextOptionsBuilder.Services.AddSingleton(); - - if (masaDbContextOptionsBuilder.Services.All(service => service.ServiceType != typeof(IUnitOfWork))) - throw new Exception("Please add UoW first."); - - masaDbContextOptionsBuilder.UseQueryFilterProvider() - .UseSaveChangesFilter(); - - return masaDbContextOptionsBuilder; - } - - private class ContractsFilter - { - } -} diff --git a/src/Data/Masa.Contrib.Data.Contracts.EF/SoftDelete/QueryFilterProvider.cs b/src/Data/Masa.Contrib.Data.Contracts.EF/SoftDelete/QueryFilterProvider.cs deleted file mode 100644 index 4abd18aae..000000000 --- a/src/Data/Masa.Contrib.Data.Contracts.EF/SoftDelete/QueryFilterProvider.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace Masa.Contrib.Data.Contracts.EF.SoftDelete; - -public class QueryFilterProvider : IQueryFilterProvider -{ - public LambdaExpression OnExecuting(IMutableEntityType entityType) - { - var parameter = Expression.Parameter(entityType.ClrType); - if (typeof(ISoftDelete).IsAssignableFrom(entityType.ClrType)) - { - var propertyMethodInfo = typeof(Microsoft.EntityFrameworkCore.EF).GetMethod("Property")!.MakeGenericMethod(typeof(bool)); - var isDeletedProperty = Expression.Call(propertyMethodInfo, parameter, Expression.Constant(nameof(ISoftDelete.IsDeleted))); - var compareExpression = Expression.MakeBinary(ExpressionType.Equal, isDeletedProperty, Expression.Constant(false)); - var lambda = Expression.Lambda(compareExpression, parameter); - return lambda; - } - - return default!; - } -} diff --git a/src/Data/Masa.Contrib.Data.Contracts.EF/SoftDelete/SoftDeleteSaveChangesFilter.cs b/src/Data/Masa.Contrib.Data.Contracts.EF/SoftDelete/SoftDeleteSaveChangesFilter.cs deleted file mode 100644 index 5fded1a40..000000000 --- a/src/Data/Masa.Contrib.Data.Contracts.EF/SoftDelete/SoftDeleteSaveChangesFilter.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Masa.Contrib.Data.Contracts.EF.SoftDelete; - -public class SoftDeleteSaveChangesFilter : ISaveChangesFilter -{ - public void OnExecuting(ChangeTracker changeTracker) - { - changeTracker.DetectChanges(); - foreach (var entity in changeTracker.Entries().Where(e => e.State == Microsoft.EntityFrameworkCore.EntityState.Deleted)) - { - if (entity.Entity is ISoftDelete) - { - entity.State = Microsoft.EntityFrameworkCore.EntityState.Modified; - entity.CurrentValues[nameof(ISoftDelete.IsDeleted)] = true; - } - } - } -} diff --git a/src/Data/Masa.Contrib.Data.Contracts.EF/_Imports.cs b/src/Data/Masa.Contrib.Data.Contracts.EF/_Imports.cs index b4a2cd361..e69de29bb 100644 --- a/src/Data/Masa.Contrib.Data.Contracts.EF/_Imports.cs +++ b/src/Data/Masa.Contrib.Data.Contracts.EF/_Imports.cs @@ -1,9 +0,0 @@ -global using Masa.BuildingBlocks.Data.Contracts; -global using Masa.BuildingBlocks.Data.UoW; -global using Masa.Contrib.Data.Contracts.EF.SoftDelete; -global using Masa.Utils.Data.EntityFrameworkCore; -global using Microsoft.EntityFrameworkCore; -global using Microsoft.EntityFrameworkCore.ChangeTracking; -global using Microsoft.EntityFrameworkCore.Metadata; -global using Microsoft.Extensions.DependencyInjection; -global using System.Linq.Expressions; diff --git a/src/Data/Masa.Contrib.Data.UoW.EF/DispatcherOptionsExtensions.cs b/src/Data/Masa.Contrib.Data.UoW.EF/DispatcherOptionsExtensions.cs index 909dd1f59..3aeee4c68 100644 --- a/src/Data/Masa.Contrib.Data.UoW.EF/DispatcherOptionsExtensions.cs +++ b/src/Data/Masa.Contrib.Data.UoW.EF/DispatcherOptionsExtensions.cs @@ -17,15 +17,10 @@ public static IDispatcherOptions UseUoW( options.Services.AddSingleton(); - options.Services.AddScoped(serviceProvider => + options.Services.AddScoped(serviceProvider => new UnitOfWork(serviceProvider) { - var dbContext = serviceProvider.GetRequiredService(); - var logger = serviceProvider.GetService>>(); - return new UnitOfWork(dbContext, logger) - { - DisableRollbackOnFailure = disableRollbackOnFailure, - UseTransaction = useTransaction - }; + DisableRollbackOnFailure = disableRollbackOnFailure, + UseTransaction = useTransaction }); if (options.Services.All(service => service.ServiceType != typeof(MasaDbContextOptions))) options.Services.AddMasaDbContext(optionsBuilder); diff --git a/src/Data/Masa.Contrib.Data.UoW.EF/Masa.Contrib.Data.UoW.EF.csproj b/src/Data/Masa.Contrib.Data.UoW.EF/Masa.Contrib.Data.UoW.EF.csproj index 083f09f91..e5d3671d0 100644 --- a/src/Data/Masa.Contrib.Data.UoW.EF/Masa.Contrib.Data.UoW.EF.csproj +++ b/src/Data/Masa.Contrib.Data.UoW.EF/Masa.Contrib.Data.UoW.EF.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/Data/Masa.Contrib.Data.UoW.EF/README.md b/src/Data/Masa.Contrib.Data.UoW.EF/README.md index a175ebff2..c8e5c975d 100644 --- a/src/Data/Masa.Contrib.Data.UoW.EF/README.md +++ b/src/Data/Masa.Contrib.Data.UoW.EF/README.md @@ -6,12 +6,11 @@ Example: ```C# Install-Package Masa.Contrib.Data.UoW.EF -Install-Package Masa.Contrib.Data.Contracts.EF +Install-Package Masa.Utils.Data.EntityFrameworkCore.SqlServer ``` ```C# builder.Services.AddEventBus(options => { options.UseUoW(dbOptions => dbOptions.UseSqlServer("server=localhost;uid=sa;pwd=P@ssw0rd;database=identity")); }); -``` - +``` \ No newline at end of file diff --git a/src/Data/Masa.Contrib.Data.UoW.EF/README.zh-CN.md b/src/Data/Masa.Contrib.Data.UoW.EF/README.zh-CN.md index dd42e6c99..85e11cbb1 100644 --- a/src/Data/Masa.Contrib.Data.UoW.EF/README.zh-CN.md +++ b/src/Data/Masa.Contrib.Data.UoW.EF/README.zh-CN.md @@ -6,12 +6,11 @@ ```C# Install-Package Masa.Contrib.Data.UoW.EF -Install-Package Masa.Contrib.Data.Contracts.EF +Install-Package Masa.Utils.Data.EntityFrameworkCore.SqlServer ``` ```C# builder.Services.AddEventBus(options => { options.UseUoW(dbOptions => dbOptions.UseSqlServer("server=localhost;uid=sa;pwd=P@ssw0rd;database=identity")); }); -``` - +``` \ No newline at end of file diff --git a/src/Data/Masa.Contrib.Data.UoW.EF/UnitOfWork.cs b/src/Data/Masa.Contrib.Data.UoW.EF/UnitOfWork.cs index f617a67a1..69b47d6db 100644 --- a/src/Data/Masa.Contrib.Data.UoW.EF/UnitOfWork.cs +++ b/src/Data/Masa.Contrib.Data.UoW.EF/UnitOfWork.cs @@ -3,6 +3,12 @@ namespace Masa.Contrib.Data.UoW.EF; public class UnitOfWork : IUnitOfWork where TDbContext : MasaDbContext { + private readonly IServiceProvider _serviceProvider; + + private DbContext? _context; + + protected DbContext Context => _context ??= _serviceProvider.GetRequiredService(); + public DbTransaction Transaction { get @@ -11,13 +17,13 @@ public DbTransaction Transaction throw new NotSupportedException("Doesn't support transaction opening"); if (TransactionHasBegun) - return _context.Database.CurrentTransaction!.GetDbTransaction(); + return Context.Database.CurrentTransaction!.GetDbTransaction(); - return _context.Database.BeginTransaction().GetDbTransaction(); + return Context.Database.BeginTransaction().GetDbTransaction(); } } - public bool TransactionHasBegun => _context.Database.CurrentTransaction != null; + public bool TransactionHasBegun => Context.Database.CurrentTransaction != null; public bool DisableRollbackOnFailure { get; set; } @@ -27,19 +33,14 @@ public DbTransaction Transaction public bool UseTransaction { get; set; } = true; - private readonly DbContext _context; - - private readonly ILogger>? _logger; - - public UnitOfWork(TDbContext dbContext, ILogger>? logger = null) + public UnitOfWork(IServiceProvider serviceProvider) { - _context = dbContext; - _logger = logger; + _serviceProvider = serviceProvider; } public async Task SaveChangesAsync(CancellationToken cancellationToken = default) { - await _context.SaveChangesAsync(cancellationToken); + await Context.SaveChangesAsync(cancellationToken); EntityState = EntityState.UnChanged; } @@ -48,7 +49,7 @@ public async Task CommitAsync(CancellationToken cancellationToken = default) if (!UseTransaction || !TransactionHasBegun) throw new NotSupportedException("Transaction not opened"); - await _context.Database.CommitTransactionAsync(cancellationToken); + await Context.Database.CommitTransactionAsync(cancellationToken); CommitState = CommitState.Commited; } @@ -57,10 +58,10 @@ public async Task RollbackAsync(CancellationToken cancellationToken = default) if (!UseTransaction || !TransactionHasBegun) throw new NotSupportedException("Transactions are not opened and rollback is not supported"); - await _context.Database.RollbackTransactionAsync(cancellationToken); + await Context.Database.RollbackTransactionAsync(cancellationToken); } - public ValueTask DisposeAsync() => _context.DisposeAsync(); + public ValueTask DisposeAsync() => Context.DisposeAsync(); - public void Dispose() => _context.Dispose(); + public void Dispose() => Context.Dispose(); } diff --git a/src/Ddd/Masa.Contrib.Ddd.Domain.Repository.EF/DispatcherOptionsExtensions.cs b/src/Ddd/Masa.Contrib.Ddd.Domain.Repository.EF/DispatcherOptionsExtensions.cs index bd4bbb6bc..61cfb533e 100644 --- a/src/Ddd/Masa.Contrib.Ddd.Domain.Repository.EF/DispatcherOptionsExtensions.cs +++ b/src/Ddd/Masa.Contrib.Ddd.Domain.Repository.EF/DispatcherOptionsExtensions.cs @@ -3,13 +3,7 @@ namespace Masa.Contrib.Ddd.Domain.Repository.EF; public static class DispatcherOptionsExtensions { public static IDispatcherOptions UseRepository( - this IDispatcherOptions options) - where TDbContext : DbContext - => options.UseRepository(AppDomain.CurrentDomain.GetAssemblies()); - - public static IDispatcherOptions UseRepository( - this IDispatcherOptions options, - params Assembly[] assemblies) + this IDispatcherOptions options) where TDbContext : DbContext { if (options.Services == null) @@ -23,7 +17,7 @@ public static IDispatcherOptions UseRepository( if (options.Services.All(service => service.ServiceType != typeof(IUnitOfWork))) throw new Exception("Please add UoW first."); - options.Services.TryAddRepository(assemblies); + options.Services.TryAddRepository(options.Assemblies); return options; } diff --git a/src/Ddd/Masa.Contrib.Ddd.Domain/README.md b/src/Ddd/Masa.Contrib.Ddd.Domain/README.md index 309899f1d..b555a3839 100644 --- a/src/Ddd/Masa.Contrib.Ddd.Domain/README.md +++ b/src/Ddd/Masa.Contrib.Ddd.Domain/README.md @@ -13,6 +13,7 @@ Install-Package Masa.Contrib.Dispatcher.Events Install-Package Masa.Contrib.Dispatcher.IntegrationEvents.Dapr Install-Package Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF Install-Package Masa.Contrib.Data.UoW.EF +Install-Package Masa.Utils.Data.EntityFrameworkCore.SqlServer ``` 1. Add DomainEventBus diff --git a/src/Ddd/Masa.Contrib.Ddd.Domain/README.zh-CN.md b/src/Ddd/Masa.Contrib.Ddd.Domain/README.zh-CN.md index 7c6371da2..e22ba2d9b 100644 --- a/src/Ddd/Masa.Contrib.Ddd.Domain/README.zh-CN.md +++ b/src/Ddd/Masa.Contrib.Ddd.Domain/README.zh-CN.md @@ -13,6 +13,7 @@ Install-Package Masa.Contrib.Dispatcher.Events Install-Package Masa.Contrib.Dispatcher.IntegrationEvents.Dapr Install-Package Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF Install-Package Masa.Contrib.Data.UoW.EF +Install-Package Masa.Utils.Data.EntityFrameworkCore.SqlServer ``` 1. 添加DomainEventBus diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Masa.Contrib.Dispatcher.Events.csproj b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Masa.Contrib.Dispatcher.Events.csproj index 31e51c60c..0625240ef 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Masa.Contrib.Dispatcher.Events.csproj +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.Events/Masa.Contrib.Dispatcher.Events.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.csproj b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.csproj index 47999595d..f62ab4315 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.csproj +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/README.md b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/README.md index 00cd40f91..dc993b783 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/README.md +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/README.md @@ -8,6 +8,7 @@ Example: Install-Package Masa.Contrib.Dispatcher.IntegrationEvents.Dapr //Send cross-process messages Install-Package Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF //Record cross-process message logs Install-Package Masa.Contrib.Data.UoW.EF //Use UnitOfWork +Install-Package Masa.Utils.Data.EntityFrameworkCore.SqlServer // Use SqlServer ``` 1. Add IIntegrationEventBus @@ -22,7 +23,7 @@ builder.Services }); ``` -> CustomerDbContext needs to inherit IntegrationEventLogContext +> CustomerDbContext needs to inherit MasaDbContext 2. Custom IntegrationEvent @@ -38,7 +39,7 @@ public class DemoIntegrationEvent : IntegrationEvent 3. Custom CustomDbContext ```C# -public class CustomDbContext : IntegrationEventLogContext +public class CustomDbContext : MasaDbContext { public DbSet Users { get; set; } = null!; diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/README.zh-CN.md b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/README.zh-CN.md index 8705c78dc..61be26831 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/README.zh-CN.md +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/README.zh-CN.md @@ -8,6 +8,7 @@ Install-Package Masa.Contrib.Dispatcher.IntegrationEvents.Dapr //发送跨进程消息 Install-Package Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF //记录跨进程消息日志 Install-Package Masa.Contrib.Data.UoW.EF //使用工作单元 +Install-Package Masa.Utils.Data.EntityFrameworkCore.SqlServer // 使用SqlServer ``` 1. 添加IIntegrationEventBus @@ -22,7 +23,7 @@ builder.Services }); ``` -> CustomerDbContext 需要继承IntegrationEventLogContext +> CustomerDbContext 需要继承MasaDbContext 2. 自定义 IntegrationEvent @@ -38,7 +39,7 @@ public class DemoIntegrationEvent : IntegrationEvent 3. 自定义CustomDbContext ```C# -public class CustomDbContext : IntegrationEventLogContext +public class CustomDbContext : MasaDbContext { public DbSet Users { get; set; } = null!; diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/DispatcherOptionsExtensions.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/DispatcherOptionsExtensions.cs index 646bc74fc..e7d443ff7 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/DispatcherOptionsExtensions.cs +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/DispatcherOptionsExtensions.cs @@ -1,31 +1,12 @@ +using Masa.BuildingBlocks.Dispatcher.Events; +using Masa.Utils.Data.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + namespace Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF; public static class DispatcherOptionsExtensions { - /// - /// IntegrationEventLogContext is a separate database - /// - /// - /// Separately specify database configuration for IntegrationEventLogContext - /// - /// - public static IDispatcherOptions UseEventLog( - this IDispatcherOptions options, - Action optionsBuilder) - { - if (options.Services == null) - throw new ArgumentNullException(nameof(options.Services)); - - if (optionsBuilder == null) - throw new ArgumentNullException(nameof(optionsBuilder)); - - if (options.Services.Any(service => service.ImplementationType == typeof(EventLogProvider))) return options; - options.Services.AddSingleton(); - - options.Services.AddCustomMasaDbContext(optionsBuilder); - return options; - } - /// /// User database with IntegrationEventLogContext merge /// User-defined DbContext need IntegrationEventLogContext inheritance @@ -34,19 +15,20 @@ public static IDispatcherOptions UseEventLog( /// /// public static IDispatcherOptions UseEventLog( - this IDispatcherOptions options) where TDbContext : IntegrationEventLogContext + this IDispatcherOptions options) where TDbContext : MasaDbContext { if (options.Services == null) throw new ArgumentNullException(nameof(options.Services)); - if (typeof(TDbContext) == typeof(IntegrationEventLogContext)) - throw new NotSupportedException( - $"{typeof(TDbContext).FullName} must be IntegrationEventLogContext derived classes, or using UseEventLog() replace UseEventLog<{typeof(TDbContext).FullName}>()"); - if (options.Services.Any(service => service.ImplementationType == typeof(EventLogProvider))) return options; + options.Services.AddSingleton(); - options.Services.TryAddScoped(serviceProvider => serviceProvider.GetRequiredService()); + //Add local message table model mapping + options.Services.TryAddEnumerable(new ServiceDescriptor(typeof(IModelCreatingProvider), + typeof(IntegrationEventLogModelCreatingProvider), ServiceLifetime.Singleton)); + options.Services.TryAddScoped(typeof(IntegrationEventLogContext), + serviceProvider => new IntegrationEventLogContext(serviceProvider.GetRequiredService())); return options; } diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/IntegrationEventLogContext.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/IntegrationEventLogContext.cs index 9eb919a83..2703650bf 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/IntegrationEventLogContext.cs +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/IntegrationEventLogContext.cs @@ -1,53 +1,10 @@ namespace Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF; -public class IntegrationEventLogContext : MasaDbContext +public class IntegrationEventLogContext { - public IntegrationEventLogContext( - MasaDbContextOptions? options = null, - MasaDbContextOptions? eventLogContext = null) - : base(eventLogContext ?? options ?? - throw new InvalidOperationException("Options extension of type 'CoreOptionsExtension' not found")) - { - } + public readonly DbContext DbContext; - public DbSet EventLogs { get; set; } + public IntegrationEventLogContext(DbContext dbContext) => DbContext = dbContext; - protected override void OnModelCreatingExecuting(ModelBuilder builder) - { - builder.Entity(ConfigureEventLogEntry); - } - - private void ConfigureEventLogEntry(EntityTypeBuilder builder) - { - builder.ToTable("IntegrationEventLog"); - - builder.HasKey(e => e.Id); - - builder.Property(e => e.Id) - .IsRequired(); - - builder.Property(e => e.Content) - .IsRequired(); - - builder.Property(e => e.CreationTime) - .IsRequired(); - - builder.Property(e => e.ModificationTime) - .IsRequired(); - - builder.Property(e => e.State) - .IsRequired(); - - builder.Property(e => e.TimesSent) - .IsRequired(); - - builder.Property(e => e.RowVersion) - .IsRowVersion(); - - builder.Property(e => e.EventTypeName) - .IsRequired(); - - builder.HasIndex(e => new { e.State, e.ModificationTime },"index_state_modificationtime"); - builder.HasIndex(e => new { e.State, e.TimesSent, e.ModificationTime },"index_state_timessent_modificationtime"); - } + public DbSet EventLogs => DbContext.Set(); } diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/IntegrationEventLogModelCreatingProvider.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/IntegrationEventLogModelCreatingProvider.cs new file mode 100644 index 000000000..3268ff542 --- /dev/null +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/IntegrationEventLogModelCreatingProvider.cs @@ -0,0 +1,43 @@ +namespace Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF; + +public class IntegrationEventLogModelCreatingProvider : IModelCreatingProvider +{ + public void Configure(ModelBuilder modelBuilder) + { + modelBuilder.Entity(ConfigureEventLogEntry); + } + + private void ConfigureEventLogEntry(EntityTypeBuilder builder) + { + builder.ToTable("IntegrationEventLog"); + + builder.HasKey(e => e.Id); + + builder.Property(e => e.Id) + .IsRequired(); + + builder.Property(e => e.Content) + .IsRequired(); + + builder.Property(e => e.CreationTime) + .IsRequired(); + + builder.Property(e => e.ModificationTime) + .IsRequired(); + + builder.Property(e => e.State) + .IsRequired(); + + builder.Property(e => e.TimesSent) + .IsRequired(); + + builder.Property(e => e.RowVersion) + .IsRowVersion(); + + builder.Property(e => e.EventTypeName) + .IsRequired(); + + builder.HasIndex(e => new { e.State, e.ModificationTime }, "index_state_modificationtime"); + builder.HasIndex(e => new { e.State, e.TimesSent, e.ModificationTime }, "index_state_timessent_modificationtime"); + } +} diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/IntegrationEventLogService.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/IntegrationEventLogService.cs index cf238b9b6..f8785766c 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/IntegrationEventLogService.cs +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/IntegrationEventLogService.cs @@ -53,12 +53,12 @@ public async Task SaveEventAsync(IIntegrationEvent @event, DbTransaction transac if (transaction == null) throw new ArgumentNullException(nameof(transaction)); - if (_eventLogContext.Database.CurrentTransaction == null) - await _eventLogContext.Database.UseTransactionAsync(transaction, Guid.NewGuid()); + if (_eventLogContext.DbContext.Database.CurrentTransaction == null) + await _eventLogContext.DbContext.Database.UseTransactionAsync(transaction, Guid.NewGuid()); - var eventLogEntry = new IntegrationEventLog(@event, _eventLogContext.Database.CurrentTransaction!.TransactionId); + var eventLogEntry = new IntegrationEventLog(@event, _eventLogContext.DbContext.Database.CurrentTransaction!.TransactionId); await _eventLogContext.EventLogs.AddAsync(eventLogEntry); - await _eventLogContext.SaveChangesAsync(); + await _eventLogContext.DbContext.SaveChangesAsync(); CheckAndDetached(eventLogEntry); } @@ -110,13 +110,13 @@ public async Task DeleteExpiresAsync(DateTime expiresAt, int batchCount = 1000, var eventLogs = _eventLogContext.EventLogs.Where(e => e.ModificationTime < expiresAt && e.State == IntegrationEventStates.Published) .OrderBy(e => e.CreationTime).Take(batchCount); _eventLogContext.EventLogs.RemoveRange(eventLogs); - await _eventLogContext.SaveChangesAsync(token); + await _eventLogContext.DbContext.SaveChangesAsync(token); - if (_eventLogContext.ChangeTracker.QueryTrackingBehavior != QueryTrackingBehavior.TrackAll) + if (_eventLogContext.DbContext.ChangeTracker.QueryTrackingBehavior != QueryTrackingBehavior.TrackAll) { foreach (var log in eventLogs) { - _eventLogContext.Entry(log).State = EntityState.Detached; + _eventLogContext.DbContext.Entry(log).State = EntityState.Detached; } } } @@ -138,7 +138,7 @@ private async Task UpdateEventStatus(Guid eventId, IntegrationEventStates status try { _eventLogContext.EventLogs.Update(eventLogEntry); - await _eventLogContext.SaveChangesAsync(); + await _eventLogContext.DbContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException ex) { @@ -150,9 +150,9 @@ private async Task UpdateEventStatus(Guid eventId, IntegrationEventStates status private void CheckAndDetached(IntegrationEventLog integrationEvent) { - if (_eventLogContext.ChangeTracker.QueryTrackingBehavior != QueryTrackingBehavior.TrackAll) + if (_eventLogContext.DbContext.ChangeTracker.QueryTrackingBehavior != QueryTrackingBehavior.TrackAll) { - _eventLogContext.Entry(integrationEvent).State = EntityState.Detached; + _eventLogContext.DbContext.Entry(integrationEvent).State = EntityState.Detached; } } } diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Internal/DbContextExtensions.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Internal/DbContextExtensions.cs deleted file mode 100644 index 713b3d3a9..000000000 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Internal/DbContextExtensions.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Internal; - -internal static class DbContextExtensions -{ - internal static IServiceCollection AddCustomMasaDbContext( - this IServiceCollection services, - Action contextAction) - where TDbContext : MasaDbContext - { - var optionsBuilder = new DbContextOptionsBuilder(); - contextAction.Invoke(optionsBuilder); - - services.AddDbContext(); - services.TryAddScoped(typeof(MasaDbContextOptions), serviceProvider => - { - return CreateMasaDbContextOptions(optionsBuilder.Options); - }); - return services; - } - - private static MasaDbContextOptions CreateMasaDbContextOptions( - DbContextOptions originOptions) - where TDbContext : MasaDbContext - { - return new MasaDbContextOptions(originOptions, new List(), new List()); - } -} diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Internal/QueryFilterProvider.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Internal/QueryFilterProvider.cs deleted file mode 100644 index 16cb5013a..000000000 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Internal/QueryFilterProvider.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Internal; - -internal abstract class QueryFilterProvider : IQueryFilterProvider -{ - public abstract LambdaExpression OnExecuting(IMutableEntityType entityType); -} diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Internal/SaveChangesFilter.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Internal/SaveChangesFilter.cs deleted file mode 100644 index c06013b21..000000000 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Internal/SaveChangesFilter.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Internal; - -internal abstract class SaveChangesFilter : ISaveChangesFilter -{ - public abstract void OnExecuting(ChangeTracker changeTracker); -} diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.csproj b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.csproj index 09675efc9..6cba6252d 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.csproj +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/README.md b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/README.md index 48d5c8461..0c7a19f49 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/README.md +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/README.md @@ -21,4 +21,4 @@ Install-Package Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF } ``` -> Tip: CustomDbContext needs to inherit IntegrationEventLogContext \ No newline at end of file +> Tip: CustomDbContext needs to inherit MasaDbContext \ No newline at end of file diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/README.zh-CN.md b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/README.zh-CN.md index a67b975a5..4b460eef1 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/README.zh-CN.md +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/README.zh-CN.md @@ -21,4 +21,4 @@ Install-Package Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF } ``` -> 提示:CustomDbContext需要继承IntegrationEventLogContext +> 提示:CustomDbContext需要继承MasaDbContext diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/_Imports.cs b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/_Imports.cs index 0ebedfeb8..d07767af4 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/_Imports.cs +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF/_Imports.cs @@ -1,11 +1,7 @@ -global using Masa.BuildingBlocks.Dispatcher.Events; global using Masa.BuildingBlocks.Dispatcher.IntegrationEvents; global using Masa.BuildingBlocks.Dispatcher.IntegrationEvents.Logs; -global using Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Internal; global using Masa.Utils.Data.EntityFrameworkCore; global using Microsoft.EntityFrameworkCore; -global using Microsoft.EntityFrameworkCore.ChangeTracking; -global using Microsoft.EntityFrameworkCore.Metadata; global using Microsoft.EntityFrameworkCore.Metadata.Builders; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.DependencyInjection.Extensions; @@ -14,5 +10,4 @@ global using System.Collections.Generic; global using System.Data.Common; global using System.Linq; -global using System.Linq.Expressions; global using System.Threading.Tasks; diff --git a/src/Service/Masa.Contrib.Service.MinimalAPIs/Masa.Contrib.Service.MinimalAPIs.csproj b/src/Service/Masa.Contrib.Service.MinimalAPIs/Masa.Contrib.Service.MinimalAPIs.csproj index cb11929e2..ea0b3de50 100644 --- a/src/Service/Masa.Contrib.Service.MinimalAPIs/Masa.Contrib.Service.MinimalAPIs.csproj +++ b/src/Service/Masa.Contrib.Service.MinimalAPIs/Masa.Contrib.Service.MinimalAPIs.csproj @@ -6,8 +6,8 @@ - - + + diff --git a/test/Masa.Contrib.Data.Contracts.EF.Tests/Domain/Entities/Courses.cs b/test/Masa.Contrib.Data.Contracts.EF.Tests/Domain/Entities/Courses.cs deleted file mode 100644 index e3c0e638c..000000000 --- a/test/Masa.Contrib.Data.Contracts.EF.Tests/Domain/Entities/Courses.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Masa.Contrib.Data.Contracts.EF.Tests.Domain.Entities; - -public class Courses : AggregateRoot -{ - public Courses() - { - Id = Guid.NewGuid(); - IsDeleted = false; - } - - public string Name { get; set; } - - public bool IsDeleted { get; set; } -} diff --git a/test/Masa.Contrib.Data.Contracts.EF.Tests/Domain/Entities/Students.cs b/test/Masa.Contrib.Data.Contracts.EF.Tests/Domain/Entities/Students.cs deleted file mode 100644 index 2bd6b8ebc..000000000 --- a/test/Masa.Contrib.Data.Contracts.EF.Tests/Domain/Entities/Students.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Masa.Contrib.Data.Contracts.EF.Tests.Domain.Entities; - -public class Students : AuditAggregateRoot -{ - public Students() - { - Id = Guid.NewGuid(); - RegisterTime = DateTime.UtcNow; - } - - public string Name { get; set; } - - public int Age { get; set; } - - public DateTime RegisterTime { get; private set; } -} diff --git a/test/Masa.Contrib.Data.Contracts.EF.Tests/Infrastructure/CustomDbContext.cs b/test/Masa.Contrib.Data.Contracts.EF.Tests/Infrastructure/CustomDbContext.cs deleted file mode 100644 index 0a756495d..000000000 --- a/test/Masa.Contrib.Data.Contracts.EF.Tests/Infrastructure/CustomDbContext.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Masa.Contrib.Data.Contracts.EF.Tests.Infrastructure; - -public class CustomDbContext : MasaDbContext -{ - public DbSet Students { get; set; } - - public DbSet Courses { get; set; } - - public CustomDbContext(MasaDbContextOptions options) : base(options) { } -} diff --git a/test/Masa.Contrib.Data.Contracts.EF.Tests/SoftDeleteTest.cs b/test/Masa.Contrib.Data.Contracts.EF.Tests/SoftDeleteTest.cs deleted file mode 100644 index b21a3435b..000000000 --- a/test/Masa.Contrib.Data.Contracts.EF.Tests/SoftDeleteTest.cs +++ /dev/null @@ -1,78 +0,0 @@ -using Masa.Contrib.Data.Contracts.EF.Tests.Infrastructure; - -namespace Masa.Contrib.Data.Contracts.EF.Tests; - -[TestClass] -public class SoftDeleteTest : IDisposable -{ - protected readonly SqliteConnection _connection; - - public SoftDeleteTest() - { - _connection = new SqliteConnection("DataSource=:memory:"); - _connection.Open(); - } - - public void Dispose() - { - _connection.Close(); - } - - [TestMethod] - public void UseNotUseUoW() - { - var services = new ServiceCollection(); - services.AddMasaDbContext(option => - { - option.UseSqlite(_connection); - Assert.ThrowsException(option.UseSoftDelete, "Please add UoW first."); - }); - } - - [TestMethod] - public void TestUseSoftDelete() - { - Mock uoW = new(); - uoW.Setup(u => u.Transaction).Verifiable(); - var services = new ServiceCollection(); - services.AddScoped(serviceProvider => uoW.Object); - services.AddMasaDbContext(option => - { - option.UseSoftDelete().UseSqlite(_connection); - }); - - var serviceProvider = services.BuildServiceProvider(); - var dbContext = serviceProvider.GetRequiredService(); - dbContext.Database.EnsureCreated(); - - dbContext.Set().Add(new Students() - { - Name = "Tom", - Age = 18 - }); - dbContext.SaveChanges(); - Assert.IsTrue(dbContext.Students.Count() == 1); - uoW.Verify(u => u.Transaction, Times.Never); - - var student = dbContext.Students.FirstOrDefault(s => s.Name == "Tom"); - Assert.IsNotNull(student); - dbContext.Set().Remove(student); - dbContext.SaveChanges(); - - Assert.IsTrue(!dbContext.Students.Any()); - } - - [TestMethod] - public void TestUseMultiSoftDelete() - { - Mock uoW = new(); - uoW.Setup(u => u.Transaction).Verifiable(); - var services = new ServiceCollection(); - services.AddScoped(serviceProvider => uoW.Object); - services.AddMasaDbContext(option => - { - option.UseSqlite(_connection); - option.UseSoftDelete().UseSoftDelete(); - }); - } -} diff --git a/test/Masa.Contrib.Data.Contracts.EF.Tests/_Imports.cs b/test/Masa.Contrib.Data.Contracts.EF.Tests/_Imports.cs index 2df7da23c..e69de29bb 100644 --- a/test/Masa.Contrib.Data.Contracts.EF.Tests/_Imports.cs +++ b/test/Masa.Contrib.Data.Contracts.EF.Tests/_Imports.cs @@ -1,10 +0,0 @@ -global using Masa.BuildingBlocks.Data.UoW; -global using Masa.BuildingBlocks.Ddd.Domain.Entities; -global using Masa.BuildingBlocks.Ddd.Domain.Entities.Auditing; -global using Masa.Contrib.Data.Contracts.EF.Tests.Domain.Entities; -global using Masa.Utils.Data.EntityFrameworkCore; -global using Microsoft.Data.Sqlite; -global using Microsoft.EntityFrameworkCore; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.VisualStudio.TestTools.UnitTesting; -global using Moq; diff --git a/test/Masa.Contrib.Data.UoW.EF.Tests/CustomerDbContext.cs b/test/Masa.Contrib.Data.UoW.EF.Tests/CustomerDbContext.cs index c8bef2b09..3577a84ea 100644 --- a/test/Masa.Contrib.Data.UoW.EF.Tests/CustomerDbContext.cs +++ b/test/Masa.Contrib.Data.UoW.EF.Tests/CustomerDbContext.cs @@ -2,12 +2,12 @@ namespace Masa.Contrib.Data.UoW.EF.Tests; public class CustomerDbContext : MasaDbContext { - public CustomerDbContext() + private static readonly Mock masaDbContextOptions = new(); + public CustomerDbContext() : this(masaDbContextOptions.Object) { - } - public CustomerDbContext(MasaDbContextOptions options) : base(options) { } + public CustomerDbContext(MasaDbContextOptions options) : base(options) { } public DbSet User { get; set; } diff --git a/test/Masa.Contrib.Data.UoW.EF.Tests/Masa.Contrib.Data.UoW.EF.Tests.csproj b/test/Masa.Contrib.Data.UoW.EF.Tests/Masa.Contrib.Data.UoW.EF.Tests.csproj index a1cbe734a..ea7704bb0 100644 --- a/test/Masa.Contrib.Data.UoW.EF.Tests/Masa.Contrib.Data.UoW.EF.Tests.csproj +++ b/test/Masa.Contrib.Data.UoW.EF.Tests/Masa.Contrib.Data.UoW.EF.Tests.csproj @@ -12,6 +12,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + all diff --git a/test/Masa.Contrib.Data.UoW.EF.Tests/TestBase.cs b/test/Masa.Contrib.Data.UoW.EF.Tests/TestBase.cs index ba64be781..c390ef322 100644 --- a/test/Masa.Contrib.Data.UoW.EF.Tests/TestBase.cs +++ b/test/Masa.Contrib.Data.UoW.EF.Tests/TestBase.cs @@ -2,16 +2,17 @@ namespace Masa.Contrib.Data.UoW.EF.Tests; public class TestBase : IDisposable { - protected readonly SqliteConnection _connection; + protected readonly string _connectionString = "DataSource=:memory:"; + protected readonly SqliteConnection Connection; protected TestBase() { - _connection = new SqliteConnection("DataSource=:memory:"); - _connection.Open(); + Connection = new SqliteConnection(_connectionString); + Connection.Open(); } public void Dispose() { - _connection.Close(); + Connection.Close(); } } diff --git a/test/Masa.Contrib.Data.UoW.EF.Tests/TestUnitOfWork.cs b/test/Masa.Contrib.Data.UoW.EF.Tests/TestUnitOfWork.cs index 73c2ba130..11a90e8c7 100644 --- a/test/Masa.Contrib.Data.UoW.EF.Tests/TestUnitOfWork.cs +++ b/test/Masa.Contrib.Data.UoW.EF.Tests/TestUnitOfWork.cs @@ -32,7 +32,7 @@ public void TestAddUoW() [TestMethod] public void TestAddUoWAndUseSqlLite() { - _options.Object.UseUoW(options => options.UseSqlite(_connection)); + _options.Object.UseUoW(options => options.UseSqlite(_connectionString)); var serviceProvider = _options.Object.Services.BuildServiceProvider(); Assert.IsNotNull(serviceProvider.GetRequiredService()); } @@ -41,8 +41,8 @@ public void TestAddUoWAndUseSqlLite() public void TestAddMultUoW() { _options.Object - .UseUoW(options => options.UseSqlite(_connection)) - .UseUoW(options => options.UseSqlite(_connection)); + .UseUoW(options => options.UseSqlite(_connectionString)) + .UseUoW(options => options.UseSqlite(_connectionString)); var serviceProvider = _options.Object.Services.BuildServiceProvider(); Assert.IsTrue(serviceProvider.GetServices().Count() == 1); @@ -55,24 +55,13 @@ public void TestTransaction() Assert.IsTrue(new Transaction(uoW.Object).UnitOfWork!.Equals(uoW.Object)); } - [TestMethod] - public async Task TestSaveChangesAsync() - { - _options.Object.UseUoW(options => options.UseSqlite(_connection)); - Mock customerDbContext = new(); - customerDbContext.Setup(dbContext => dbContext.SaveChangesAsync(default)).Verifiable(); - var uoW = new UnitOfWork(customerDbContext.Object, null); - await uoW.SaveChangesAsync(default); - customerDbContext.Verify(dbContext => dbContext.SaveChangesAsync(default), Times.Once); - } - [TestMethod] public async Task TestUseTranscationAsync() { - _options.Object.UseUoW(options => options.UseSqlite(_connection)); + _options.Object.UseUoW(options => options.DbContextOptionsBuilder.UseSqlite(Connection)); var serviceProvider = _options.Object.Services.BuildServiceProvider(); var dbContext = serviceProvider.GetRequiredService(); - dbContext.Database.EnsureCreated(); + await dbContext.Database.EnsureCreatedAsync(); var uoW = serviceProvider.GetRequiredService(); var transaction = uoW.Transaction; @@ -84,17 +73,17 @@ public async Task TestUseTranscationAsync() await uoW.SaveChangesAsync(); await uoW.RollbackAsync(); - Assert.IsTrue(dbContext.User.ToList().Count() == 0); + Assert.IsTrue(!dbContext.User.ToList().Any()); } [TestMethod] public async Task TestNotUseTranscationAsync() { - _options.Object.UseUoW(options => options.UseSqlite(_connection)); + _options.Object.UseUoW(options => options.DbContextOptionsBuilder.UseSqlite(Connection)); var serviceProvider = _options.Object.Services.BuildServiceProvider(); var dbContext = serviceProvider.GetRequiredService(); - dbContext.Database.EnsureCreated(); - var uoW = new UnitOfWork(dbContext, null); + await dbContext.Database.EnsureCreatedAsync(); + var uoW = new UnitOfWork(serviceProvider); Users user = new Users() { @@ -108,22 +97,22 @@ public async Task TestNotUseTranscationAsync() [TestMethod] public async Task TestNotTransactionCommitAsync() { - _options.Object.UseUoW(options => options.UseSqlite(_connection)); + _options.Object.UseUoW(options => options.UseSqlite(_connectionString)); var serviceProvider = _options.Object.Services.BuildServiceProvider(); var dbContext = serviceProvider.GetRequiredService(); - dbContext.Database.EnsureCreated(); - var uoW = new UnitOfWork(dbContext, null); + await dbContext.Database.EnsureCreatedAsync(); + var uoW = new UnitOfWork(serviceProvider); await Assert.ThrowsExceptionAsync(async () => await uoW.CommitAsync()); } [TestMethod] public async Task TestCommitAsync() { - _options.Object.UseUoW(options => options.UseSqlite(_connection)); + _options.Object.UseUoW(options => options.DbContextOptionsBuilder.UseSqlite(Connection)); var serviceProvider = _options.Object.Services.BuildServiceProvider(); var dbContext = serviceProvider.GetRequiredService(); - dbContext.Database.EnsureCreated(); - var uoW = new UnitOfWork(dbContext, null); + await dbContext.Database.EnsureCreatedAsync(); + var uoW = new UnitOfWork(serviceProvider); var user = new Users() { Name = "Tom" @@ -139,10 +128,10 @@ public async Task TestCommitAsync() [TestMethod] public async Task TestOpenRollbackAsync() { - _options.Object.UseUoW(options => options.UseSqlite(_connection)); + _options.Object.UseUoW(options => options.DbContextOptionsBuilder.UseSqlite(Connection)); var serviceProvider = _options.Object.Services.BuildServiceProvider(); var dbContext = serviceProvider.GetRequiredService(); - dbContext.Database.EnsureCreated(); + await dbContext.Database.EnsureCreatedAsync(); var uoW = serviceProvider.GetRequiredService(); var user = new Users(); var transcation = uoW.Transaction; @@ -156,10 +145,10 @@ public async Task TestOpenRollbackAsync() public async Task TestAddLoggerAndOpenRollbackAsync() { _options.Object.Services.AddLogging(); - _options.Object.UseUoW(options => options.UseSqlite(_connection)); + _options.Object.UseUoW(options => options.DbContextOptionsBuilder.UseSqlite(Connection)); var serviceProvider = _options.Object.Services.BuildServiceProvider(); var dbContext = serviceProvider.GetRequiredService(); - dbContext.Database.EnsureCreated(); + await dbContext.Database.EnsureCreatedAsync(); var uoW = serviceProvider.GetRequiredService(); var user = new Users(); var transcation = uoW.Transaction; diff --git a/test/Masa.Contrib.Data.UoW.EF.Tests/_Imports.cs b/test/Masa.Contrib.Data.UoW.EF.Tests/_Imports.cs index 489619ad4..24516a06e 100644 --- a/test/Masa.Contrib.Data.UoW.EF.Tests/_Imports.cs +++ b/test/Masa.Contrib.Data.UoW.EF.Tests/_Imports.cs @@ -1,6 +1,7 @@ global using Masa.BuildingBlocks.Data.UoW; global using Masa.BuildingBlocks.Dispatcher.Events; global using Masa.Utils.Data.EntityFrameworkCore; +global using Masa.Utils.Data.EntityFrameworkCore.Sqlite; global using Microsoft.Data.Sqlite; global using Microsoft.EntityFrameworkCore; global using Microsoft.EntityFrameworkCore.Metadata.Builders; diff --git a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/BaseRepositoryTest.cs b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/BaseRepositoryTest.cs index 28d90048a..0e75231af 100644 --- a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/BaseRepositoryTest.cs +++ b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/BaseRepositoryTest.cs @@ -37,17 +37,20 @@ public void TestUseCustomRepositoryAndNotImplementation() Mock uoW = new(); _services.AddScoped(_ => uoW.Object); + Assembly[] assemblies = { typeof(TestBase).Assembly, typeof(IUserRepository).Assembly }; + _dispatcherOptions.Setup(option => option.Assemblies).Returns(assemblies).Verifiable(); Assert.ThrowsException(() - => _dispatcherOptions.Object.UseRepository(typeof(TestBase).Assembly, typeof(IUserRepository).Assembly) + => _dispatcherOptions.Object.UseRepository() ); } [TestMethod] public void TestNullUnitOfWork() { + _dispatcherOptions.Setup(option => option.Assemblies).Returns(_assemblies).Verifiable(); var ex = Assert.ThrowsException(() => { - _dispatcherOptions.Object.UseRepository(_assemblies); + _dispatcherOptions.Object.UseRepository(); }); Assert.IsTrue(ex.Message == "Please add UoW first."); } @@ -56,20 +59,21 @@ public void TestNullUnitOfWork() public void TestNullAssembly() { _services.AddScoped(typeof(IUnitOfWork), _ => _uoW.Object); - _services.AddDbContext(options => options.UseSqlite(_connection)); + _services.AddDbContext(options => options.UseSqlite(Connection)); Assert.ThrowsException(() => { - _dispatcherOptions.Object.UseRepository(null!); + _dispatcherOptions.Object.UseRepository(); }); } [TestMethod] public void TestAddMultRepository() { + _dispatcherOptions.Setup(option => option.Assemblies).Returns(_assemblies).Verifiable(); _services.AddScoped(typeof(IUnitOfWork), _ => _uoW.Object); - _services.AddMasaDbContext(options => options.UseSqlite(_connection)); - _dispatcherOptions.Object.UseRepository(_assemblies).UseRepository(); + _services.AddMasaDbContext(options => options.DbContextOptionsBuilder.UseSqlite(Connection)); + _dispatcherOptions.Object.UseRepository().UseRepository(); var serviceProvider = _services.BuildServiceProvider(); var repository = serviceProvider.GetServices>(); diff --git a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/RepositoryTest.cs b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/RepositoryTest.cs index 5814adcb4..4bf7eaa10 100644 --- a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/RepositoryTest.cs +++ b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/RepositoryTest.cs @@ -24,20 +24,22 @@ public async Task InitializeAsync(Action? action) }; _dispatcherOptions = new Mock(); _dispatcherOptions.Setup(options => options.Services).Returns(() => _services); + _dispatcherOptions.Setup(options => options.Assemblies).Returns(() => _assemblies); if (action == null) - _services.AddMasaDbContext(options => options.UseSqlite(_connection)); + _services.AddMasaDbContext(options => options.DbContextOptionsBuilder.UseSqlite(Connection)); else action.Invoke(_services); + var serviceProvider = _services.BuildServiceProvider(); _dbContext = _services.BuildServiceProvider().GetRequiredService(); await _dbContext.Database.EnsureCreatedAsync(); - _uoW = new UnitOfWork(_dbContext); + _uoW = new UnitOfWork(serviceProvider); _dispatcherOptions.Object.UseUoW(); } private async Task> InitDataAsync() { - _dispatcherOptions.Object.UseRepository(_assemblies); + _dispatcherOptions.Object.UseRepository(); var serviceProvider = _services.BuildServiceProvider(); var orders = new List @@ -118,7 +120,7 @@ public async Task TestRemoveRangeAsync() [TestMethod] public async Task TestGetPaginatedListAsync() { - _dispatcherOptions.Object.UseRepository(_assemblies); + _dispatcherOptions.Object.UseRepository(); var serviceProvider = _services.BuildServiceProvider(); var customizeOrderRepository = serviceProvider.GetRequiredService(); @@ -190,7 +192,7 @@ public async Task TestGetPaginatedListAsync() [TestMethod] public async Task TestTranscationFailedAsync() { - _dispatcherOptions.Object.UseRepository(_assemblies); + _dispatcherOptions.Object.UseRepository(); var serviceProvider = _services.BuildServiceProvider(); var repository = serviceProvider.GetRequiredService(); var order = new Orders(1) @@ -204,7 +206,7 @@ public async Task TestTranscationFailedAsync() [TestMethod] public async Task TestTranscationSucceededAsync() { - _dispatcherOptions.Object.UseRepository(_assemblies); + _dispatcherOptions.Object.UseRepository(); var serviceProvider = _services.BuildServiceProvider(); var repository = serviceProvider.GetRequiredService(); var order = new Orders(1) @@ -222,11 +224,11 @@ public async Task TestUpdateAsync() await InitializeAsync(services => services.AddMasaDbContext(options => { - options.UseSqlite(_connection) + options.DbContextOptionsBuilder.UseSqlite(Connection) .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); })); - _dispatcherOptions.Object.UseRepository(_assemblies); + _dispatcherOptions.Object.UseRepository(); var serviceProvider = _services.BuildServiceProvider(); var dbContext = serviceProvider.GetRequiredService(); @@ -282,7 +284,7 @@ public async Task TestFindAsync() [TestMethod] public void TestCustomizeOrderRepository() { - _dispatcherOptions.Object.UseRepository(_assemblies); + _dispatcherOptions.Object.UseRepository(); var serviceProvider = _services.BuildServiceProvider(); var customizeOrderRepository = serviceProvider.GetService(); @@ -362,13 +364,13 @@ public async Task TestDbTransactionAsync() public async Task TestServiceLifeAsync() { var services = new ServiceCollection(); - services.AddMasaDbContext(options => options.UseSqlite(_connection)); + services.AddMasaDbContext(options => options.DbContextOptionsBuilder.UseSqlite(Connection)); var serviceProvider = services.BuildServiceProvider(); await using (var scope = serviceProvider.CreateAsyncScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); - var uow = new UnitOfWork(dbContext); + var uow = new UnitOfWork(scope.ServiceProvider); var repository = new Repository(dbContext, uow); await repository.AddAsync(new Orders(1) { diff --git a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/TestBase.cs b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/TestBase.cs index c73370a09..5df1d8488 100644 --- a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/TestBase.cs +++ b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/TestBase.cs @@ -2,16 +2,17 @@ namespace Masa.Contrib.Ddd.Domain.Repository.EF.Tests; public class TestBase : IDisposable { - protected readonly SqliteConnection _connection; + protected readonly string ConnectionString = "DataSource=:memory:"; + protected readonly SqliteConnection Connection; protected TestBase() { - _connection = new SqliteConnection("DataSource=:memory:"); - _connection.Open(); + Connection = new SqliteConnection(ConnectionString); + Connection.Open(); } public void Dispose() { - _connection.Close(); + Connection.Close(); } } diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/_Imports.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/_Imports.cs index 59e2109b7..3fcad16c1 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/_Imports.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/_Imports.cs @@ -4,16 +4,15 @@ global using Masa.BuildingBlocks.Dispatcher.IntegrationEvents; global using Masa.BuildingBlocks.Dispatcher.IntegrationEvents.Logs; global using Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Options; +global using Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Processor; global using Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests.Events; +global using Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests.Internal; global using Masa.Utils.Models.Config; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.Logging; +global using Microsoft.Extensions.Logging.Abstractions; global using Microsoft.Extensions.Options; global using Microsoft.VisualStudio.TestTools.UnitTesting; global using Moq; global using System.Data.Common; global using System.Reflection; -global using Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests.Internal; -global using Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Processor; -global using Microsoft.Extensions.Logging.Abstractions; - diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/Infrastructure/CustomDbContext.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/Infrastructure/CustomDbContext.cs index 0356c8d9d..096c1c55c 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/Infrastructure/CustomDbContext.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/Infrastructure/CustomDbContext.cs @@ -1,6 +1,6 @@ namespace Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests.Infrastructure; -internal class CustomDbContext : IntegrationEventLogContext +internal class CustomDbContext : MasaDbContext { public DbSet Users { get; set; } = null!; diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/IntegrationEventLogContextTest.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/IntegrationEventLogContextTest.cs index 3bc2bd7aa..e96cf62a1 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/IntegrationEventLogContextTest.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/IntegrationEventLogContextTest.cs @@ -6,9 +6,11 @@ public class IntegrationEventLogContextTest : TestBase [TestMethod] public void TestCreateDbContext() { - var serviceProvider = CreateDefaultProvider(); - var dbContext = serviceProvider.GetRequiredService(); - var entity = dbContext.Model.GetEntityTypes().FirstOrDefault(entityType => entityType.Name == typeof(IntegrationEventLog).FullName)!; + var serviceProvider = CreateDefaultProvider(option => option.UseEventLog()); + + var customDbContext = serviceProvider.GetRequiredService(); + var entity = customDbContext.Model.GetEntityTypes() + .FirstOrDefault(entityType => entityType.Name == typeof(IntegrationEventLog).FullName)!; Assert.IsTrue(entity.GetTableName() == "IntegrationEventLog"); var properties = entity.GetProperties().ToList(); @@ -19,5 +21,34 @@ public void TestCreateDbContext() Assert.IsFalse(properties.Where(x => x.Name == "State").Select(x => x.IsNullable).FirstOrDefault()); Assert.IsFalse(properties.Where(x => x.Name == "TimesSent").Select(x => x.IsNullable).FirstOrDefault()); Assert.IsFalse(properties.Where(x => x.Name == "EventTypeName").Select(x => x.IsNullable).FirstOrDefault()); + + var integrationEventLogDbContext = serviceProvider.GetRequiredService(); + Assert.IsTrue(customDbContext == integrationEventLogDbContext.DbContext); + } + + [TestMethod] + public void TestAddDbContext() + { + var services = new ServiceCollection(); + services.AddDbContext(options => options.UseSqlite(Connection)); + var serviceProvider = services.BuildServiceProvider(); + + var dbContext = serviceProvider.GetService(); + Assert.IsTrue(dbContext == null); + + Assert.ThrowsException(() => serviceProvider.GetService()); + } + + [TestMethod] + public void TestUseEventLog() + { + var dispatcherOptions = new DispatcherOptions(new ServiceCollection()); + dispatcherOptions.Services.AddDbContext(options => options.UseSqlite(Connection)); + dispatcherOptions.UseEventLog(); + var serviceProvider = dispatcherOptions.Services.BuildServiceProvider(); + + Assert.ThrowsException(() => serviceProvider.GetService()); + + Assert.ThrowsException(() => serviceProvider.GetService()); } } diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/IntegrationEventLogServiceTest.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/IntegrationEventLogServiceTest.cs index 891d7237e..e6a2d629d 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/IntegrationEventLogServiceTest.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/IntegrationEventLogServiceTest.cs @@ -10,10 +10,9 @@ public async Task TestNullDbTransactionAsync() var @event = new OrderPaymentSucceededIntegrationEvent() { OrderId = "1234567890123", - PaymentTime = (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + PaymentTime = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds }; - var serviceProvider = CreateDefaultProvider(); - var dbContext = serviceProvider.GetRequiredService(); + var serviceProvider = CreateDefaultProvider(option => option.UseEventLog()); var eventLogService = serviceProvider.GetRequiredService(); await Assert.ThrowsExceptionAsync(async () => await eventLogService.SaveEventAsync(@event, transaction)); } @@ -23,7 +22,7 @@ public void TestMultUseEventLogService() { var serviceProvider = CreateDefaultProvider(options => { - options.UseEventLog(dbContextOptionsBuilder => dbContextOptionsBuilder.UseSqlite(_connection)); + options.UseEventLog(); }); Assert.IsTrue(serviceProvider.GetServices().Count() == 1); } @@ -32,14 +31,10 @@ public void TestMultUseEventLogService() public void TestNullServices() { var options = new DispatcherOptions(null!); - Assert.ThrowsException(() => { options.UseEventLog(options => { options.UseSqlite(base._connection); }); }); - } - - [TestMethod] - public void TestNullDbContextOptionsBuilder() - { - var options = new DispatcherOptions(new ServiceCollection()); - Assert.ThrowsException(() => { options.UseEventLog(null!); }); + Assert.ThrowsException(() => + { + options.UseEventLog(); + }); } [TestMethod] @@ -50,25 +45,18 @@ public void TestUseCustomDbContextByNullServices() Assert.ThrowsException(() => options.UseEventLog()); } - [TestMethod] - public void TestGenericEventLog() - { - var options = new DispatcherOptions(new ServiceCollection()); - Assert.ThrowsException(() => options.UseEventLog()); - } - [TestMethod] public async Task TestCustomDbContextAsync() { var options = new DispatcherOptions(new ServiceCollection()); - options.Services.AddMasaDbContext(options => - options.UseSqlite(_connection).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)); + options.Services.AddMasaDbContext(optionsBuilder + => optionsBuilder.UseSqlite(ConnectionString).DbContextOptionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)); var integrationEventBus = new Mock(); integrationEventBus.Setup(e => e.GetAllEventTypes()).Returns(() => AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()) .Where(type => typeof(IIntegrationEvent).IsAssignableFrom(type))); - options.Services.AddScoped(serviceProvider => integrationEventBus.Object); + options.Services.AddScoped(_ => integrationEventBus.Object); options.Services.AddScoped(); @@ -80,25 +68,18 @@ public async Task TestCustomDbContextAsync() var @event = new OrderPaymentSucceededIntegrationEvent() { OrderId = "1234567890123", - PaymentTime = (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + PaymentTime = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds }; var dbContext = serviceProvider.GetRequiredService(); await dbContext.Database.EnsureCreatedAsync(); - // using (var transaction = await dbContext.Database.BeginTransactionAsync()) - // { - // await eventLogService.SaveEventAsync(@event, - // Microsoft.EntityFrameworkCore.Storage.DbContextTransactionExtensions.GetDbTransaction(transaction)); - // - // await eventLogService.RetrieveEventLogsPendingToPublishAsync(transaction.TransactionId); - // } } [TestMethod] public async Task TestAddMultEventLog() { var options = new DispatcherOptions(new ServiceCollection()); - options.Services.AddMasaDbContext(options => options.UseSqlite(_connection)); + options.Services.AddMasaDbContext(optionsBuilder => optionsBuilder.UseSqlite(ConnectionString)); var integrationEventBus = new Mock(); integrationEventBus.Setup(e => e.GetAllEventTypes()).Returns(() => @@ -116,29 +97,10 @@ public async Task TestAddMultEventLog() var @event = new OrderPaymentSucceededIntegrationEvent() { OrderId = "1234567890123", - PaymentTime = (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + PaymentTime = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds }; var dbContext = serviceProvider.GetRequiredService(); await dbContext.Database.EnsureCreatedAsync(); - // using (var transaction = dbContext.Database.BeginTransaction()) - // { - // await eventLogService.SaveEventAsync(@event, - // Microsoft.EntityFrameworkCore.Storage.DbContextTransactionExtensions.GetDbTransaction(transaction)); - // - // await eventLogService.RetrieveEventLogsPendingToPublishAsync(transaction.TransactionId); - // } - } - - [TestMethod] - public void TestGetIntegrationEventLogService() - { - var services = new ServiceCollection(); - services.AddDbContext(options => options.UseSqlite(_connection)); - var serviceProvider = services.BuildServiceProvider(); - Assert.ThrowsException(() => - { - var dbContext = serviceProvider.GetServices(); - }); } } diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests.csproj b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests.csproj index 55da15d84..f96a49f85 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests.csproj +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests.csproj @@ -13,6 +13,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/TestBase.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/TestBase.cs index 33d9ca88d..6db9f6b81 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/TestBase.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/TestBase.cs @@ -1,20 +1,19 @@ -using System.Reflection; - namespace Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests; -public class TestBase +public class TestBase : IDisposable { - protected readonly SqliteConnection _connection; + protected readonly string ConnectionString = "DataSource=:memory:"; + protected readonly SqliteConnection Connection; protected TestBase() { - _connection = new SqliteConnection("DataSource=:memory:"); - _connection.Open(); + Connection = new SqliteConnection(ConnectionString); + Connection.Open(); } public void Dispose() { - _connection.Close(); + Connection.Close(); } protected IServiceProvider CreateDefaultProvider(Action? action = null) @@ -22,7 +21,7 @@ protected IServiceProvider CreateDefaultProvider(Action? acti var services = new ServiceCollection(); services.AddScoped(); var options = new DispatcherOptions(services); - options.UseEventLog(options => options.UseSqlite(_connection)); + services.AddMasaDbContext(builder => builder.UseSqlite(ConnectionString)); action?.Invoke(options); var integrationEventBus = new Mock(); diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/_Imports.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/_Imports.cs index 27a7955bc..cfbaca7e3 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/_Imports.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/_Imports.cs @@ -6,10 +6,12 @@ global using Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests.Events; global using Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests.Infrastructure; global using Masa.Utils.Data.EntityFrameworkCore; +global using Masa.Utils.Data.EntityFrameworkCore.Sqlite; global using Microsoft.Data.Sqlite; global using Microsoft.EntityFrameworkCore; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.VisualStudio.TestTools.UnitTesting; global using Moq; global using System.Data.Common; +global using System.Reflection; global using System.Text.Json.Serialization;