mirror of https://github.com/abpframework/abp.git
28 changed files with 1359 additions and 30 deletions
@ -0,0 +1,81 @@ |
|||
using System; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DependencyInjection; |
|||
|
|||
internal static class ServiceCollectionDecorateExtensions |
|||
{ |
|||
internal static IServiceCollection Decorate<TService>( |
|||
this IServiceCollection services, |
|||
Func<IServiceProvider, TService, TService> decorator) |
|||
where TService : class |
|||
{ |
|||
// The container resolves the last registration.
|
|||
for (var i = services.Count - 1; i >= 0; i--) |
|||
{ |
|||
var descriptor = services[i]; |
|||
if (descriptor.ServiceType != typeof(TService) || descriptor.IsKeyedService) |
|||
{ |
|||
continue; |
|||
} |
|||
|
|||
// The same service collection can be decorated more than once, for example when ApplyServices runs again.
|
|||
if (descriptor.ImplementationFactory?.Target is Decorator<TService>) |
|||
{ |
|||
break; |
|||
} |
|||
|
|||
// The original registration stays in the container under its own key, so the container still creates and disposes it.
|
|||
var innerServiceKey = new object(); |
|||
services[i] = new ServiceDescriptor( |
|||
typeof(TService), |
|||
new Decorator<TService>(innerServiceKey, decorator).Create, |
|||
descriptor.Lifetime); |
|||
services.Add(CreateInnerDescriptor(descriptor, innerServiceKey)); |
|||
break; |
|||
} |
|||
|
|||
return services; |
|||
} |
|||
|
|||
private static ServiceDescriptor CreateInnerDescriptor(ServiceDescriptor descriptor, object innerServiceKey) |
|||
{ |
|||
if (descriptor.ImplementationType != null) |
|||
{ |
|||
return new ServiceDescriptor(descriptor.ServiceType, innerServiceKey, descriptor.ImplementationType, descriptor.Lifetime); |
|||
} |
|||
|
|||
if (descriptor.ImplementationFactory != null) |
|||
{ |
|||
var implementationFactory = descriptor.ImplementationFactory; |
|||
return new ServiceDescriptor(descriptor.ServiceType, innerServiceKey, (provider, _) => implementationFactory(provider), descriptor.Lifetime); |
|||
} |
|||
|
|||
return new ServiceDescriptor(descriptor.ServiceType, innerServiceKey, descriptor.ImplementationInstance!); |
|||
} |
|||
|
|||
private sealed class Decorator<TService> |
|||
where TService : class |
|||
{ |
|||
private readonly object _innerServiceKey; |
|||
private readonly Func<IServiceProvider, TService, TService> _decorator; |
|||
|
|||
public Decorator(object innerServiceKey, Func<IServiceProvider, TService, TService> decorator) |
|||
{ |
|||
_innerServiceKey = innerServiceKey; |
|||
_decorator = decorator; |
|||
} |
|||
|
|||
public object Create(IServiceProvider serviceProvider) |
|||
{ |
|||
var inner = serviceProvider.GetRequiredKeyedService<TService>(_innerServiceKey); |
|||
var service = _decorator(serviceProvider, inner); |
|||
if (service == null || ReferenceEquals(service, inner)) |
|||
{ |
|||
throw new AbpException($"The decorator of {typeof(TService).FullName} must return a new object."); |
|||
} |
|||
|
|||
return service; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,56 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq.Expressions; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.EntityFrameworkCore.Infrastructure; |
|||
using Microsoft.EntityFrameworkCore.Query; |
|||
using Microsoft.EntityFrameworkCore.Storage; |
|||
using Microsoft.EntityFrameworkCore.Update; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.GlobalFilters; |
|||
|
|||
public class AbpEfCoreDatabase : IDatabase |
|||
{ |
|||
protected IDatabase InnerDatabase { get; } |
|||
protected AbpEfCoreCurrentDbContext AbpEfCoreCurrentDbContext { get; } |
|||
protected ICurrentDbContext CurrentDbContext { get; } |
|||
|
|||
public AbpEfCoreDatabase( |
|||
IDatabase innerDatabase, |
|||
AbpEfCoreCurrentDbContext abpEfCoreCurrentDbContext, |
|||
ICurrentDbContext currentDbContext) |
|||
{ |
|||
InnerDatabase = innerDatabase; |
|||
AbpEfCoreCurrentDbContext = abpEfCoreCurrentDbContext; |
|||
CurrentDbContext = currentDbContext; |
|||
} |
|||
|
|||
public virtual int SaveChanges(IList<IUpdateEntry> entries) |
|||
{ |
|||
return InnerDatabase.SaveChanges(entries); |
|||
} |
|||
|
|||
public virtual Task<int> SaveChangesAsync(IList<IUpdateEntry> entries, CancellationToken cancellationToken = default) |
|||
{ |
|||
return InnerDatabase.SaveChangesAsync(entries, cancellationToken); |
|||
} |
|||
|
|||
public virtual Func<QueryContext, TResult> CompileQuery<TResult>(Expression query, bool async) |
|||
{ |
|||
using (AbpEfCoreCurrentDbContext.BeginQueryCompilation(CurrentDbContext.Context as IAbpEfCoreDbFunctionContext, query)) |
|||
{ |
|||
return InnerDatabase.CompileQuery<TResult>(query, async); |
|||
} |
|||
} |
|||
|
|||
#pragma warning disable EF9100
|
|||
public virtual Expression<Func<QueryContext, TResult>> CompileQueryExpression<TResult>(Expression query, bool async) |
|||
{ |
|||
using (AbpEfCoreCurrentDbContext.BeginQueryCompilation(CurrentDbContext.Context as IAbpEfCoreDbFunctionContext, query)) |
|||
{ |
|||
return InnerDatabase.CompileQueryExpression<TResult>(query, async); |
|||
} |
|||
} |
|||
#pragma warning restore EF9100
|
|||
} |
|||
@ -0,0 +1,77 @@ |
|||
using System; |
|||
using System.Linq; |
|||
using Microsoft.EntityFrameworkCore; |
|||
using Microsoft.EntityFrameworkCore.Infrastructure; |
|||
using Microsoft.EntityFrameworkCore.Query; |
|||
using Microsoft.EntityFrameworkCore.Storage; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.EntityFrameworkCore.GlobalFilters; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
public class AbpDbContextOptionsExtension_Tests |
|||
{ |
|||
[Fact] |
|||
public void Should_Create_And_Delete_InMemory_Database() |
|||
{ |
|||
var options = new DbContextOptionsBuilder() |
|||
.UseInMemoryDatabase(Guid.NewGuid().ToString()) |
|||
.AddAbpDbContextOptionsExtension() |
|||
.Options; |
|||
|
|||
using var context = new DbContext(options); |
|||
context.GetService<IDatabase>().ShouldNotBeOfType<AbpEfCoreDatabase>(); |
|||
context.Database.EnsureCreated().ShouldBeTrue(); |
|||
context.Database.EnsureDeleted().ShouldBeTrue(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Apply_Services_Once() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
services.AddEntityFrameworkSqlite(); |
|||
|
|||
new AbpDbContextOptionsExtension().ApplyServices(services); |
|||
new AbpDbContextOptionsExtension().ApplyServices(services); |
|||
|
|||
services.Count(x => x.ServiceType == typeof(IDatabase) && x.IsKeyedService).ShouldBe(1); |
|||
services.Count(x => x.ServiceType == typeof(AbpEfCoreCurrentDbContext)).ShouldBe(1); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Apply_Services_Again_After_The_Database_Provider() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
var extension = new AbpDbContextOptionsExtension(); |
|||
|
|||
extension.ApplyServices(services); |
|||
services.AddEntityFrameworkSqlite(); |
|||
extension.ApplyServices(services); |
|||
|
|||
services.Count(x => x.ServiceType == typeof(IDatabase) && x.IsKeyedService).ShouldBe(1); |
|||
services.Count(x => x.ServiceType == typeof(ICompiledQueryCacheKeyGenerator) && x.IsKeyedService).ShouldBe(1); |
|||
services.Count(x => x.ServiceType == typeof(AbpEfCoreCurrentDbContext)).ShouldBe(1); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Decorate_Database_Registered_After_Applying_Services() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
var extension = new AbpDbContextOptionsExtension(); |
|||
services.AddEntityFrameworkSqlite(); |
|||
extension.ApplyServices(services); |
|||
services.AddScoped<IDatabase>(provider => ActivatorUtilities.CreateInstance<RelationalDatabase>(provider)); |
|||
extension.ApplyServices(services); |
|||
|
|||
using var serviceProvider = services.BuildServiceProvider(); |
|||
var options = new DbContextOptionsBuilder() |
|||
.UseSqlite("Data Source=:memory:") |
|||
.UseInternalServiceProvider(serviceProvider) |
|||
.Options; |
|||
|
|||
using var context = new DbContext(options); |
|||
context.GetService<IDatabase>().ShouldBeOfType<AbpEfCoreDatabase>(); |
|||
} |
|||
} |
|||
@ -0,0 +1,11 @@ |
|||
using System; |
|||
using Volo.Abp.Domain.Entities; |
|||
using Volo.Abp.MultiTenancy; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
public class CompiledQueryCacheMultiTenantRow : Entity<Guid>, IMultiTenant |
|||
{ |
|||
public Guid? TenantId { get; set; } |
|||
public string Name { get; set; } |
|||
} |
|||
@ -0,0 +1,11 @@ |
|||
using System; |
|||
using Volo.Abp.Data; |
|||
using Volo.Abp.Domain.Entities; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
public class CompiledQueryCacheSoftDeleteRow : Entity<Guid>, ISoftDelete |
|||
{ |
|||
public bool IsDeleted { get; set; } |
|||
public string Name { get; set; } |
|||
} |
|||
@ -0,0 +1,46 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.EntityFrameworkCore.Storage; |
|||
using Microsoft.EntityFrameworkCore.Update; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
public class CompiledQueryCacheTestDatabase : RelationalDatabase, IDisposable |
|||
{ |
|||
private readonly CompiledQueryCacheTestDatabaseRecorder _recorder; |
|||
|
|||
public CompiledQueryCacheTestDatabase( |
|||
DatabaseDependencies dependencies, |
|||
RelationalDatabaseDependencies relationalDependencies, |
|||
CompiledQueryCacheTestDatabaseRecorder recorder) |
|||
: base(dependencies, relationalDependencies) |
|||
{ |
|||
_recorder = recorder; |
|||
} |
|||
|
|||
public override int SaveChanges(IList<IUpdateEntry> entries) |
|||
{ |
|||
Interlocked.Increment(ref _recorder.SaveChangesCount); |
|||
return base.SaveChanges(entries); |
|||
} |
|||
|
|||
public override Task<int> SaveChangesAsync(IList<IUpdateEntry> entries, CancellationToken cancellationToken = default) |
|||
{ |
|||
Interlocked.Increment(ref _recorder.SaveChangesCount); |
|||
return base.SaveChangesAsync(entries, cancellationToken); |
|||
} |
|||
|
|||
public void Dispose() |
|||
{ |
|||
Interlocked.Increment(ref _recorder.DisposeCount); |
|||
} |
|||
} |
|||
|
|||
public class CompiledQueryCacheTestDatabaseRecorder |
|||
{ |
|||
public int SaveChangesCount; |
|||
|
|||
public int DisposeCount; |
|||
} |
|||
@ -0,0 +1,49 @@ |
|||
using System; |
|||
using System.Linq.Expressions; |
|||
using Microsoft.EntityFrameworkCore.Diagnostics; |
|||
using Volo.Abp.EntityFrameworkCore.GlobalFilters; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
public class CompiledQueryCacheTestHooks |
|||
{ |
|||
public Action<CompiledQueryCacheTestDbContext> OnQueryCompilationStarting { get; set; } |
|||
|
|||
public Action OnGetCompiledQueryCacheKey { get; set; } |
|||
} |
|||
|
|||
public class CompiledQueryCacheTestInterceptor : IQueryExpressionInterceptor |
|||
{ |
|||
private readonly CompiledQueryCacheTestHooks _hooks; |
|||
|
|||
public CompiledQueryCacheTestInterceptor(CompiledQueryCacheTestHooks hooks) |
|||
{ |
|||
_hooks = hooks; |
|||
} |
|||
|
|||
public Expression QueryCompilationStarting(Expression queryExpression, QueryExpressionEventData eventData) |
|||
{ |
|||
if (eventData.Context is CompiledQueryCacheTestDbContext dbContext) |
|||
{ |
|||
_hooks.OnQueryCompilationStarting?.Invoke(dbContext); |
|||
} |
|||
|
|||
return queryExpression; |
|||
} |
|||
} |
|||
|
|||
public class CompiledQueryCacheTestKeyProvider : IAbpEfCoreCompiledQueryCacheKeyProvider |
|||
{ |
|||
private readonly CompiledQueryCacheTestHooks _hooks; |
|||
|
|||
public CompiledQueryCacheTestKeyProvider(CompiledQueryCacheTestHooks hooks) |
|||
{ |
|||
_hooks = hooks; |
|||
} |
|||
|
|||
public string GetCompiledQueryCacheKey() |
|||
{ |
|||
_hooks.OnGetCompiledQueryCacheKey?.Invoke(); |
|||
return null; |
|||
} |
|||
} |
|||
@ -0,0 +1,13 @@ |
|||
using Volo.Abp.Autofac; |
|||
using Volo.Abp.EntityFrameworkCore.Sqlite; |
|||
using Volo.Abp.Modularity; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
[DependsOn(typeof(AbpEntityFrameworkCoreSqliteModule), typeof(AbpAutofacModule))] |
|||
public class CompiledQueryCacheTestModuleWithAbpServicesFirst : CompiledQueryCacheTestModuleBase |
|||
{ |
|||
protected override bool UseDbFunction => true; |
|||
|
|||
protected override bool AddAbpServicesBeforeDatabaseProvider => true; |
|||
} |
|||
@ -0,0 +1,13 @@ |
|||
using Volo.Abp.Autofac; |
|||
using Volo.Abp.EntityFrameworkCore.Sqlite; |
|||
using Volo.Abp.Modularity; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
[DependsOn(typeof(AbpEntityFrameworkCoreSqliteModule), typeof(AbpAutofacModule))] |
|||
public class CompiledQueryCacheTestModuleWithDatabaseFactory : CompiledQueryCacheTestModuleBase |
|||
{ |
|||
protected override bool UseDbFunction => true; |
|||
|
|||
protected override bool AddCustomDatabase => true; |
|||
} |
|||
@ -0,0 +1,43 @@ |
|||
using Microsoft.EntityFrameworkCore; |
|||
using Microsoft.EntityFrameworkCore.Query.Internal; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Volo.Abp.Autofac; |
|||
using Volo.Abp.EntityFrameworkCore.Sqlite; |
|||
using Volo.Abp.Modularity; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
[DependsOn(typeof(AbpEntityFrameworkCoreSqliteModule), typeof(AbpAutofacModule))] |
|||
public class CompiledQueryCacheTestModuleWithQueryCompiler : CompiledQueryCacheTestModuleBase |
|||
{ |
|||
private readonly CompiledQueryCacheTestQueryCompilerOptions _queryCompilerOptions = new(); |
|||
|
|||
protected override bool UseDbFunction => true; |
|||
|
|||
protected override bool UseExternalEfServiceProvider => false; |
|||
|
|||
public override void ConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
context.Services.AddSingleton(_queryCompilerOptions); |
|||
base.ConfigureServices(context); |
|||
} |
|||
|
|||
protected override void ConfigureEfOptions(DbContextOptionsBuilder options) |
|||
{ |
|||
#pragma warning disable EF1001
|
|||
if (_queryCompilerOptions.ReplaceImplementationType) |
|||
{ |
|||
options.ReplaceService<IQueryCompiler, QueryCompiler, CompiledQueryCacheTestQueryCompiler>(); |
|||
} |
|||
else |
|||
{ |
|||
options.ReplaceService<IQueryCompiler, CompiledQueryCacheTestQueryCompiler>(); |
|||
} |
|||
#pragma warning restore EF1001
|
|||
} |
|||
} |
|||
|
|||
public class CompiledQueryCacheTestQueryCompilerOptions |
|||
{ |
|||
public bool ReplaceImplementationType { get; set; } |
|||
} |
|||
@ -0,0 +1,56 @@ |
|||
using System; |
|||
using System.Linq.Expressions; |
|||
using System.Threading; |
|||
using Microsoft.EntityFrameworkCore.Query; |
|||
using Microsoft.EntityFrameworkCore.Query.Internal; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
#pragma warning disable EF1001
|
|||
// A custom query compiler that an application registers with ReplaceService.
|
|||
public class CompiledQueryCacheTestQueryCompiler : IQueryCompiler |
|||
{ |
|||
private readonly QueryCompiler _inner; |
|||
|
|||
public int ExecuteCount { get; private set; } |
|||
|
|||
public int CreateCompiledQueryCount { get; private set; } |
|||
|
|||
public CompiledQueryCacheTestQueryCompiler(IServiceProvider serviceProvider) |
|||
{ |
|||
_inner = ActivatorUtilities.CreateInstance<QueryCompiler>(serviceProvider); |
|||
} |
|||
|
|||
public TResult Execute<TResult>(Expression query) |
|||
{ |
|||
ExecuteCount++; |
|||
return _inner.Execute<TResult>(query); |
|||
} |
|||
|
|||
public TResult ExecuteAsync<TResult>(Expression query, CancellationToken cancellationToken) |
|||
{ |
|||
ExecuteCount++; |
|||
return _inner.ExecuteAsync<TResult>(query, cancellationToken); |
|||
} |
|||
|
|||
public Func<QueryContext, TResult> CreateCompiledQuery<TResult>(Expression query) |
|||
{ |
|||
CreateCompiledQueryCount++; |
|||
return _inner.CreateCompiledQuery<TResult>(query); |
|||
} |
|||
|
|||
public Func<QueryContext, TResult> CreateCompiledAsyncQuery<TResult>(Expression query) |
|||
{ |
|||
CreateCompiledQueryCount++; |
|||
return _inner.CreateCompiledAsyncQuery<TResult>(query); |
|||
} |
|||
|
|||
#pragma warning disable EF9100
|
|||
public Expression<Func<QueryContext, TResult>> PrecompileQuery<TResult>(Expression query, bool async) |
|||
{ |
|||
return _inner.PrecompileQuery<TResult>(query, async); |
|||
} |
|||
#pragma warning restore EF9100
|
|||
} |
|||
#pragma warning restore EF1001
|
|||
@ -0,0 +1,25 @@ |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.EntityFrameworkCore; |
|||
using Shouldly; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Volo.Abp.TestApp.Testing; |
|||
using Volo.Abp.Uow; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
public class CompiledQueryCache_AbpServicesFirst_Tests : TestAppTestBase<CompiledQueryCacheTestModuleWithAbpServicesFirst> |
|||
{ |
|||
[Fact] |
|||
public async Task Should_Not_Run_Query_Without_Filters() |
|||
{ |
|||
using var uow = GetRequiredService<IUnitOfWorkManager>().Begin(); |
|||
using var tenant = GetRequiredService<ICurrentTenant>().Change(CompiledQueryCacheTestModuleBase.TenantA); |
|||
var context = GetRequiredService<CompiledQueryCacheTestDbContext>(); |
|||
context.UseDbFunction().ShouldBeTrue(); |
|||
|
|||
var exception = await Should.ThrowAsync<AbpException>(() => context.Rows.Select(row => row.Name).ToListAsync()); |
|||
exception.Message.ShouldContain("AbpDbContextOptionsExtension"); |
|||
} |
|||
} |
|||
@ -0,0 +1,49 @@ |
|||
using System; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.EntityFrameworkCore; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Volo.Abp.Uow; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
public class CompiledQueryCache_DatabaseFactory_Tests : CompiledQueryCacheTestBase<CompiledQueryCacheTestModuleWithDatabaseFactory> |
|||
{ |
|||
protected override bool UseDbFunction => true; |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Run_Compiled_Query_First_Run_Inside_Another_Query_Without_Filters() |
|||
{ |
|||
var countRows = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => db.Rows.Count()); |
|||
|
|||
var exception = await Should.ThrowAsync<InvalidOperationException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
Task.FromResult(db.Rows.Where(row => row.Name.Length > countRows(db)).Select(row => row.Name).ToList()))); |
|||
exception.InnerException.ShouldBeOfType<AbpException>(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Keep_Using_And_Disposing_The_Custom_Database() |
|||
{ |
|||
var recorder = GetRequiredService<CompiledQueryCacheTestDatabaseRecorder>(); |
|||
var disposeCount = recorder.DisposeCount; |
|||
|
|||
using (var scope = ServiceProvider.CreateScope()) |
|||
{ |
|||
using var uow = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>().Begin(); |
|||
using var tenant = scope.ServiceProvider.GetRequiredService<ICurrentTenant>().Change(CompiledQueryCacheTestModuleBase.TenantA); |
|||
var db = scope.ServiceProvider.GetRequiredService<CompiledQueryCacheTestDbContext>(); |
|||
|
|||
var row = await db.Rows.SingleAsync(); |
|||
row.Name = "A-saved"; |
|||
await db.SaveChangesAsync(); |
|||
await uow.CompleteAsync(); |
|||
} |
|||
|
|||
recorder.SaveChangesCount.ShouldBe(1); |
|||
recorder.DisposeCount.ShouldBeGreaterThan(disposeCount); |
|||
} |
|||
} |
|||
@ -0,0 +1,75 @@ |
|||
using System; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.EntityFrameworkCore; |
|||
using Microsoft.EntityFrameworkCore.Infrastructure; |
|||
using Microsoft.EntityFrameworkCore.Query.Internal; |
|||
using Shouldly; |
|||
using Volo.Abp.Data; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Volo.Abp.TestApp.Testing; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
#pragma warning disable EF1001
|
|||
public class CompiledQueryCache_QueryCompiler_Tests : TestAppTestBase<CompiledQueryCacheTestModuleWithQueryCompiler> |
|||
{ |
|||
[Theory] |
|||
[InlineData(false)] |
|||
[InlineData(true)] |
|||
public async Task Should_Use_The_Replaced_Query_Compiler(bool replaceImplementationType) |
|||
{ |
|||
GetRequiredService<CompiledQueryCacheTestQueryCompilerOptions>().ReplaceImplementationType = replaceImplementationType; |
|||
|
|||
await WithUnitOfWorkAsync(async () => |
|||
{ |
|||
var currentTenant = GetRequiredService<ICurrentTenant>(); |
|||
using (currentTenant.Change(CompiledQueryCacheTestModuleBase.TenantA)) |
|||
{ |
|||
var db = GetRequiredService<CompiledQueryCacheTestDbContext>(); |
|||
db.UseDbFunction().ShouldBeTrue(); |
|||
var queryCompiler = db.GetService<IQueryCompiler>().ShouldBeOfType<CompiledQueryCacheTestQueryCompiler>(); |
|||
|
|||
(await db.Rows.Select(row => row.Name).ToListAsync()).ShouldBe(new[] { "A-live" }); |
|||
using (currentTenant.Change(CompiledQueryCacheTestModuleBase.TenantB)) |
|||
{ |
|||
db.Rows.Select(row => row.Name).ToList().ShouldBe(new[] { "B-live" }); |
|||
} |
|||
|
|||
queryCompiler.ExecuteCount.ShouldBe(2); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData(false)] |
|||
[InlineData(true)] |
|||
public async Task Should_Not_Run_Compiled_Query_First_Run_Inside_Another_Query_Without_Filters(bool replaceImplementationType) |
|||
{ |
|||
GetRequiredService<CompiledQueryCacheTestQueryCompilerOptions>().ReplaceImplementationType = replaceImplementationType; |
|||
var countRows = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => db.Rows.Count()); |
|||
|
|||
await WithUnitOfWorkAsync(async () => |
|||
{ |
|||
using (GetRequiredService<ICurrentTenant>().Change(CompiledQueryCacheTestModuleBase.TenantA)) |
|||
{ |
|||
var db = GetRequiredService<CompiledQueryCacheTestDbContext>(); |
|||
var queryCompiler = db.GetService<IQueryCompiler>().ShouldBeOfType<CompiledQueryCacheTestQueryCompiler>(); |
|||
var dataFilter = GetRequiredService<IDataFilter>(); |
|||
|
|||
using (dataFilter.Disable<ISoftDelete>()) |
|||
using (dataFilter.Disable<IMultiTenant>()) |
|||
{ |
|||
var exception = Should.Throw<InvalidOperationException>(() => |
|||
db.Rows.Where(row => row.Name.Length > countRows(db)).Select(row => row.Name).ToList()); |
|||
exception.InnerException.ShouldBeOfType<AbpException>(); |
|||
} |
|||
|
|||
queryCompiler.CreateCompiledQueryCount.ShouldBe(1); |
|||
(await db.Rows.Select(row => row.Name).ToListAsync()).ShouldBe(new[] { "A-live" }); |
|||
} |
|||
}); |
|||
} |
|||
} |
|||
#pragma warning restore EF1001
|
|||
@ -1,6 +1,283 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.EntityFrameworkCore; |
|||
using Microsoft.EntityFrameworkCore.Infrastructure; |
|||
using Microsoft.EntityFrameworkCore.Query; |
|||
using Microsoft.EntityFrameworkCore.Storage; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.Data; |
|||
using Volo.Abp.EntityFrameworkCore.GlobalFilters; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
public class CompiledQueryCache_Tests : CompiledQueryCacheTestBase<CompiledQueryCacheTestModule> |
|||
{ |
|||
protected override bool UseDbFunction => true; |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Run_Compiled_Query_Without_SoftDelete_Filter() |
|||
{ |
|||
var query = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => db.SoftDeleteRows.Select(x => x.Name)); |
|||
|
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => Task.FromResult(query(db).ToList()))); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Run_Compiled_Query_Without_MultiTenant_Filter() |
|||
{ |
|||
var query = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => db.MultiTenantRows.Select(x => x.Name)); |
|||
|
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => Task.FromResult(query(db).ToList()))); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Run_Compiled_Query_First_Run_Inside_Another_Query_Without_Filters() |
|||
{ |
|||
var countRows = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => db.Rows.Count()); |
|||
|
|||
// EF Core wraps the exceptions thrown while it evaluates the parameters of the outer query.
|
|||
var exception = await Should.ThrowAsync<InvalidOperationException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
Task.FromResult(db.Rows.Where(row => row.Name.Length > countRows(db)).Select(row => row.Name).ToList()))); |
|||
exception.InnerException.ShouldBeOfType<AbpException>(); |
|||
|
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => Task.FromResult(new[] { countRows(db).ToString() }.ToList()))); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Run_Compiled_Async_Query_First_Run_Inside_Another_Query_Without_Filters() |
|||
{ |
|||
var countRowsAsync = EF.CompileAsyncQuery((CompiledQueryCacheTestDbContext db) => db.Rows.Count()); |
|||
|
|||
var exception = await Should.ThrowAsync<InvalidOperationException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
Task.FromResult(db.Rows |
|||
.Where(row => row.Name.Length > countRowsAsync(db).GetAwaiter().GetResult()) |
|||
.Select(row => row.Name) |
|||
.ToList()))); |
|||
exception.InnerException.ShouldBeOfType<AbpException>(); |
|||
|
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, async db => new[] { (await countRowsAsync(db)).ToString() }.ToList())); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData(false)] |
|||
[InlineData(true)] |
|||
public async Task Should_Not_Run_Compiled_Query_First_Run_Inside_Another_Query_With_Disabled_Filters(bool asyncCompiledQuery) |
|||
{ |
|||
var countRows = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => db.Rows.Count()); |
|||
var countRowsAsync = EF.CompileAsyncQuery((CompiledQueryCacheTestDbContext db) => db.Rows.Count()); |
|||
var dataFilter = GetRequiredService<IDataFilter>(); |
|||
|
|||
using (dataFilter.Disable<ISoftDelete>()) |
|||
using (dataFilter.Disable<IMultiTenant>()) |
|||
{ |
|||
var exception = await Should.ThrowAsync<InvalidOperationException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
Task.FromResult(asyncCompiledQuery |
|||
? db.Rows.Where(row => row.Name.Length > countRowsAsync(db).GetAwaiter().GetResult()).Select(row => row.Name).ToList() |
|||
: db.Rows.Where(row => row.Name.Length > countRows(db)).Select(row => row.Name).ToList()))); |
|||
exception.InnerException.ShouldBeOfType<AbpException>(); |
|||
} |
|||
|
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, async db => |
|||
new[] { (asyncCompiledQuery ? await countRowsAsync(db) : countRows(db)).ToString() }.ToList())); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Run_Compiled_Query_First_Run_While_Another_Query_Is_Compiled_Without_Filters() |
|||
{ |
|||
var countRows = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => db.Rows.Count()); |
|||
var countRowsAsync = EF.CompileAsyncQuery((CompiledQueryCacheTestDbContext db) => db.Rows.Count()); |
|||
var hooks = GetRequiredService<CompiledQueryCacheTestHooks>(); |
|||
|
|||
hooks.OnQueryCompilationStarting = db => |
|||
{ |
|||
hooks.OnQueryCompilationStarting = null; |
|||
countRows(db); |
|||
}; |
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
Task.FromResult(db.Rows.TagWith(Guid.NewGuid().ToString()).Select(row => row.Name).ToList()))); |
|||
|
|||
hooks.OnQueryCompilationStarting = db => |
|||
{ |
|||
hooks.OnQueryCompilationStarting = null; |
|||
countRowsAsync(db).GetAwaiter().GetResult(); |
|||
}; |
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
db.Rows.TagWith(Guid.NewGuid().ToString()).Select(row => row.Name).ToListAsync())); |
|||
|
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => Task.FromResult(new[] { countRows(db).ToString() }.ToList()))); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Run_Compiled_Query_First_Run_While_Cache_Key_Is_Generated_Without_Filters() |
|||
{ |
|||
var countRows = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => db.Rows.Count()); |
|||
var hooks = GetRequiredService<CompiledQueryCacheTestHooks>(); |
|||
|
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
{ |
|||
hooks.OnGetCompiledQueryCacheKey = () => |
|||
{ |
|||
hooks.OnGetCompiledQueryCacheKey = null; |
|||
countRows(db); |
|||
}; |
|||
|
|||
return Task.FromResult(db.Rows.TagWith(Guid.NewGuid().ToString()).Select(row => row.Name).ToList()); |
|||
})); |
|||
|
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => Task.FromResult(new[] { countRows(db).ToString() }.ToList()))); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData(false)] |
|||
[InlineData(true)] |
|||
public async Task Should_Not_Precompile_Query_While_Cache_Key_Is_Generated_Without_Filters(bool async) |
|||
{ |
|||
var hooks = GetRequiredService<CompiledQueryCacheTestHooks>(); |
|||
|
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
{ |
|||
hooks.OnGetCompiledQueryCacheKey = () => |
|||
{ |
|||
hooks.OnGetCompiledQueryCacheKey = null; |
|||
#pragma warning disable EF1001, EF9100
|
|||
var queryCompiler = db.GetService<Microsoft.EntityFrameworkCore.Query.Internal.IQueryCompiler>(); |
|||
var query = db.Rows.Select(row => row.Name).Expression; |
|||
if (async) |
|||
{ |
|||
queryCompiler.PrecompileQuery<IAsyncEnumerable<string>>(query, true); |
|||
} |
|||
else |
|||
{ |
|||
queryCompiler.PrecompileQuery<IEnumerable<string>>(query, false); |
|||
} |
|||
#pragma warning restore EF1001, EF9100
|
|||
}; |
|||
|
|||
return Task.FromResult(db.Rows.TagWith(Guid.NewGuid().ToString()).Select(row => row.Name).ToList()); |
|||
})); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Provide_Current_DbContext_While_Cache_Key_Is_Generated() |
|||
{ |
|||
var hooks = GetRequiredService<CompiledQueryCacheTestHooks>(); |
|||
|
|||
await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, async db => |
|||
{ |
|||
var currentDbContext = db.GetService<AbpEfCoreCurrentDbContext>(); |
|||
var contexts = new List<IAbpEfCoreDbFunctionContext>(); |
|||
hooks.OnGetCompiledQueryCacheKey = () => contexts.Add(currentDbContext.Context); |
|||
try |
|||
{ |
|||
db.Rows.Select(row => row.Name).ToList(); |
|||
await db.Rows.Select(row => row.Name).ToListAsync(); |
|||
} |
|||
finally |
|||
{ |
|||
hooks.OnGetCompiledQueryCacheKey = null; |
|||
} |
|||
|
|||
contexts.Count.ShouldBe(2); |
|||
contexts.ShouldAllBe(context => context == db); |
|||
return new List<string>(); |
|||
}); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Compile_Query_With_Cache_Key_Generated_Outside_Of_Query_Provider() |
|||
{ |
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
{ |
|||
var expression = ((IQueryable<CompiledQueryCacheTestRow>)db.Rows).Expression; |
|||
db.GetService<ICompiledQueryCacheKeyGenerator>().GenerateCacheKey(expression, false); |
|||
db.GetService<IDatabase>().CompileQuery<IEnumerable<CompiledQueryCacheTestRow>>(expression, false); |
|||
return Task.FromResult(new List<string>()); |
|||
})); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Apply_Filters_To_Normal_Query_After_Compiled_Query_Failed() |
|||
{ |
|||
var countRows = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => db.Rows.Count()); |
|||
|
|||
await Should.ThrowAsync<InvalidOperationException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
Task.FromResult(db.Rows.Where(row => row.Name.Length > countRows(db)).Select(row => row.Name).ToList()))); |
|||
|
|||
(await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
db.Rows.OrderBy(row => row.Name).Select(row => row.Name).ToListAsync())) |
|||
.ShouldBe(new[] { "A-live" }); |
|||
|
|||
(await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, async db => |
|||
{ |
|||
Should.Throw<InvalidOperationException>(() => db.Rows.Where(row => row.Name.Length > countRows(db)).Select(row => row.Name).ToList()); |
|||
return await db.Rows.OrderBy(row => row.Name).Select(row => row.Name).ToListAsync(); |
|||
})) |
|||
.ShouldBe(new[] { "A-live" }); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Run_Compiled_Query_That_Ignores_Filters() |
|||
{ |
|||
var countAllRows = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => db.Rows.IgnoreQueryFilters().Count()); |
|||
|
|||
(await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => Task.FromResult(new[] { countAllRows(db).ToString() }.ToList()))) |
|||
.ShouldBe(new[] { CompiledQueryCacheTestModuleBase.Rows.Length.ToString() }); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Not_Allow_Replacing_Database() |
|||
{ |
|||
var options = new DbContextOptionsBuilder<CompiledQueryCacheTestDbContext>() |
|||
.UseSqlite("Data Source=:memory:") |
|||
.ReplaceService<IDatabase, RelationalDatabase>() |
|||
.AddAbpDbContextOptionsExtension() |
|||
.Options; |
|||
|
|||
Should.Throw<AbpException>(() => new CompiledQueryCacheTestDbContext(options).Dispose()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Compile_Query_Inside_Another_Query_Without_Filters() |
|||
{ |
|||
var exception = await Should.ThrowAsync<InvalidOperationException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => |
|||
Task.FromResult(db.Rows.Where(row => row.Name.Length > CompileRowsQuery(db)).Select(row => row.Name).ToList()))); |
|||
exception.InnerException.ShouldBeOfType<AbpException>(); |
|||
} |
|||
|
|||
private static int CompileRowsQuery(CompiledQueryCacheTestDbContext db) |
|||
{ |
|||
db.GetService<IDatabase>().CompileQuery<IEnumerable<CompiledQueryCacheTestRow>>(((IQueryable<CompiledQueryCacheTestRow>)db.Rows).Expression, false); |
|||
return 0; |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Run_Compiled_Async_Query_Without_Filters() |
|||
{ |
|||
var query = EF.CompileAsyncQuery((CompiledQueryCacheTestDbContext db) => db.Rows.Select(x => x.Name)); |
|||
|
|||
await Should.ThrowAsync<AbpException>(() => |
|||
RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => ToListAsync(query(db)))); |
|||
} |
|||
} |
|||
|
|||
@ -1,6 +1,58 @@ |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.EntityFrameworkCore; |
|||
using Shouldly; |
|||
using Volo.Abp.Data; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DataFiltering.CompiledQueryCache; |
|||
|
|||
public class CompiledQueryCache_WithoutDbFunction_Tests : CompiledQueryCacheTestBase<CompiledQueryCacheTestModuleWithoutDbFunction> |
|||
{ |
|||
protected override bool UseDbFunction => false; |
|||
|
|||
[Fact] |
|||
public async Task Should_Apply_Filters_To_Compiled_Queries() |
|||
{ |
|||
var query = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => |
|||
db.Rows.OrderBy(x => x.Name).Select(x => x.Name)); |
|||
var asyncQuery = EF.CompileAsyncQuery((CompiledQueryCacheTestDbContext db) => |
|||
db.Rows.OrderBy(x => x.Name).Select(x => x.Name)); |
|||
|
|||
(await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => Task.FromResult(query(db).ToList()))) |
|||
.ShouldBe(new[] { "A-live" }); |
|||
(await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantB, db => Task.FromResult(query(db).ToList()))) |
|||
.ShouldBe(new[] { "B-live" }); |
|||
(await RunInTenantAsync(null, db => ToListAsync(asyncQuery(db)))) |
|||
.ShouldBe(new[] { "Host-live" }); |
|||
(await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => ToListAsync(asyncQuery(db)))) |
|||
.ShouldBe(new[] { "A-live" }); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Read_Filter_State_On_Every_Run_Of_Compiled_Query() |
|||
{ |
|||
var query = EF.CompileQuery((CompiledQueryCacheTestDbContext db) => |
|||
db.Rows.OrderBy(x => x.Name).Select(x => x.Name)); |
|||
var dataFilter = GetRequiredService<IDataFilter>(); |
|||
|
|||
(await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => Task.FromResult(query(db).ToList()))) |
|||
.ShouldBe(new[] { "A-live" }); |
|||
|
|||
using (dataFilter.Disable<ISoftDelete>()) |
|||
{ |
|||
(await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => Task.FromResult(query(db).ToList()))) |
|||
.ShouldBe(new[] { "A-deleted", "A-live" }); |
|||
} |
|||
|
|||
using (dataFilter.Disable<IMultiTenant>()) |
|||
{ |
|||
(await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => Task.FromResult(query(db).ToList()))) |
|||
.ShouldBe(new[] { "A-live", "B-live", "Host-live" }); |
|||
} |
|||
|
|||
(await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, db => Task.FromResult(query(db).ToList()))) |
|||
.ShouldBe(new[] { "A-live" }); |
|||
} |
|||
} |
|||
|
|||
@ -0,0 +1,160 @@ |
|||
using System; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.DependencyInjection; |
|||
|
|||
public class ServiceCollectionDecorateExtensions_Tests |
|||
{ |
|||
[Fact] |
|||
public void Should_Decorate_Type_Registration() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
services.AddScoped<IDecorateTestService, DecorateTestService>(); |
|||
|
|||
services.Decorate<IDecorateTestService>((_, inner) => new DecorateTestServiceDecorator(inner)); |
|||
|
|||
using var provider = services.BuildServiceProvider(); |
|||
using var scope = provider.CreateScope(); |
|||
var service = scope.ServiceProvider.GetRequiredService<IDecorateTestService>(); |
|||
service.ShouldBeOfType<DecorateTestServiceDecorator>().Inner.ShouldBeOfType<DecorateTestService>(); |
|||
scope.ServiceProvider.GetRequiredService<IDecorateTestService>().ShouldBeSameAs(service); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Decorate_The_Last_Registration() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
services.AddScoped<IDecorateTestService, DecorateTestService>(); |
|||
services.AddScoped<IDecorateTestService, OtherDecorateTestService>(); |
|||
|
|||
services.Decorate<IDecorateTestService>((_, inner) => new DecorateTestServiceDecorator(inner)); |
|||
|
|||
using var provider = services.BuildServiceProvider(); |
|||
provider.GetRequiredService<IDecorateTestService>() |
|||
.ShouldBeOfType<DecorateTestServiceDecorator>().Inner.ShouldBeOfType<OtherDecorateTestService>(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Dispose_Inner_Service_Created_By_Factory() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
services.AddScoped<IDecorateTestService>(_ => new DisposableDecorateTestService()); |
|||
|
|||
services.Decorate<IDecorateTestService>((_, inner) => new DecorateTestServiceDecorator(inner)); |
|||
|
|||
using var provider = services.BuildServiceProvider(); |
|||
DisposableDecorateTestService inner; |
|||
using (var scope = provider.CreateScope()) |
|||
{ |
|||
inner = scope.ServiceProvider.GetRequiredService<IDecorateTestService>() |
|||
.ShouldBeOfType<DecorateTestServiceDecorator>().Inner.ShouldBeOfType<DisposableDecorateTestService>(); |
|||
inner.DisposeCount.ShouldBe(0); |
|||
} |
|||
|
|||
inner.DisposeCount.ShouldBe(1); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Not_Dispose_Inner_Service_Registered_As_Instance() |
|||
{ |
|||
var instance = new DisposableDecorateTestService(); |
|||
var services = new ServiceCollection(); |
|||
services.AddSingleton<IDecorateTestService>(instance); |
|||
|
|||
services.Decorate<IDecorateTestService>((_, inner) => new DecorateTestServiceDecorator(inner)); |
|||
|
|||
using (var provider = services.BuildServiceProvider()) |
|||
{ |
|||
provider.GetRequiredService<IDecorateTestService>() |
|||
.ShouldBeOfType<DecorateTestServiceDecorator>().Inner.ShouldBeSameAs(instance); |
|||
} |
|||
|
|||
instance.DisposeCount.ShouldBe(0); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Not_Allow_Returning_The_Decorated_Service() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
services.AddScoped<IDecorateTestService, DisposableDecorateTestService>(); |
|||
|
|||
services.Decorate<IDecorateTestService>((_, inner) => inner); |
|||
|
|||
using var provider = services.BuildServiceProvider(); |
|||
using var scope = provider.CreateScope(); |
|||
Should.Throw<AbpException>(() => scope.ServiceProvider.GetRequiredService<IDecorateTestService>()); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Decorate_Once() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
services.AddScoped<IDecorateTestService, DecorateTestService>(); |
|||
|
|||
services.Decorate<IDecorateTestService>((_, inner) => new DecorateTestServiceDecorator(inner)); |
|||
services.Decorate<IDecorateTestService>((_, inner) => new DecorateTestServiceDecorator(inner)); |
|||
|
|||
using var provider = services.BuildServiceProvider(); |
|||
provider.GetRequiredService<IDecorateTestService>() |
|||
.ShouldBeOfType<DecorateTestServiceDecorator>().Inner.ShouldBeOfType<DecorateTestService>(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Decorate_Registration_Added_After_Decoration() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
services.AddScoped<IDecorateTestService, DecorateTestService>(); |
|||
services.Decorate<IDecorateTestService>((_, inner) => new DecorateTestServiceDecorator(inner)); |
|||
services.AddScoped<IDecorateTestService, OtherDecorateTestService>(); |
|||
|
|||
services.Decorate<IDecorateTestService>((_, inner) => new DecorateTestServiceDecorator(inner)); |
|||
|
|||
using var provider = services.BuildServiceProvider(); |
|||
provider.GetRequiredService<IDecorateTestService>() |
|||
.ShouldBeOfType<DecorateTestServiceDecorator>().Inner.ShouldBeOfType<OtherDecorateTestService>(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Not_Change_Services_Without_Registration() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
|
|||
services.Decorate<IDecorateTestService>((_, inner) => new DecorateTestServiceDecorator(inner)); |
|||
|
|||
services.ShouldBeEmpty(); |
|||
} |
|||
|
|||
public interface IDecorateTestService |
|||
{ |
|||
} |
|||
|
|||
public class DecorateTestService : IDecorateTestService |
|||
{ |
|||
} |
|||
|
|||
public class OtherDecorateTestService : IDecorateTestService |
|||
{ |
|||
} |
|||
|
|||
public class DisposableDecorateTestService : IDecorateTestService, IDisposable |
|||
{ |
|||
public int DisposeCount { get; private set; } |
|||
|
|||
public void Dispose() |
|||
{ |
|||
DisposeCount++; |
|||
} |
|||
} |
|||
|
|||
public class DecorateTestServiceDecorator : IDecorateTestService |
|||
{ |
|||
public IDecorateTestService Inner { get; } |
|||
|
|||
public DecorateTestServiceDecorator(IDecorateTestService inner) |
|||
{ |
|||
Inner = inner; |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue