Browse Source

Merge remote-tracking branch 'origin/rel-10.7' into auto-merge-forward/rel-10.7-to-dev-88

pull/26291/head
github-actions[bot] 1 month ago
parent
commit
5f6b4283d9
  1. 4
      docs/en/Community-Articles/2024-07-01-Use_User-Defined_Function_Mapping_For_Global_Filter/POST.md
  2. 35
      docs/en/framework/infrastructure/data-filtering.md
  3. 23
      docs/en/release-info/migration-guides/abp-10-7.md
  4. 4
      framework/src/Volo.Abp.EntityFrameworkCore/Microsoft/Extensions/DependencyInjection/AbpEfCoreModelBuilderExtensions.cs
  5. 28
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContextOptionsExtension.cs
  6. 34
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpEntityQueryProvider.cs
  7. 81
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/DependencyInjection/ServiceCollectionDecorateExtensions.cs
  8. 2
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/GlobalFilters/AbpCompiledQueryCacheKeyGenerator.cs
  9. 56
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/GlobalFilters/AbpEfCoreCurrentDbContext.cs
  10. 56
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/GlobalFilters/AbpEfCoreDatabase.cs
  11. 77
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/AbpDbContextOptionsExtension_Tests.cs
  12. 11
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheMultiTenantRow.cs
  13. 11
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheSoftDeleteRow.cs
  14. 46
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestBase.cs
  15. 46
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestDatabase.cs
  16. 4
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestDbContext.cs
  17. 49
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestHooks.cs
  18. 59
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestModuleBase.cs
  19. 13
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestModuleWithAbpServicesFirst.cs
  20. 13
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestModuleWithDatabaseFactory.cs
  21. 43
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestModuleWithQueryCompiler.cs
  22. 56
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestQueryCompiler.cs
  23. 25
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCache_AbpServicesFirst_Tests.cs
  24. 49
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCache_DatabaseFactory_Tests.cs
  25. 75
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCache_QueryCompiler_Tests.cs
  26. 277
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCache_Tests.cs
  27. 52
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCache_WithoutDbFunction_Tests.cs
  28. 160
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DependencyInjection/ServiceCollectionDecorateExtensions_Tests.cs

4
docs/en/Community-Articles/2024-07-01-Use_User-Defined_Function_Mapping_For_Global_Filter/POST.md

@ -69,7 +69,9 @@ protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntit
var isActive = args[0];
var boolParam = args[1];
if (abpEfCoreCurrentDbContext.Context?.DataFilter.IsEnabled<IIsActive>() == true)
// Context is null when the query is compiled by EF.CompileQuery or EF.CompileAsyncQuery.
var dbContext = abpEfCoreCurrentDbContext.Context ?? throw new InvalidOperationException("The IIsActive filter cannot be applied to EF.CompileQuery or EF.CompileAsyncQuery.");
if (dbContext.DataFilter.IsEnabled<IIsActive>())
{
// isActive == true
return new SqlBinaryExpression(

35
docs/en/framework/infrastructure/data-filtering.md

@ -224,9 +224,9 @@ protected override bool ShouldFilterEntity<TEntity>(IMutableEntityType entityTyp
return base.ShouldFilterEntity<TEntity>(entityType);
}
protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>(ModelBuilder modelBuilder)
protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>(ModelBuilder modelBuilder, EntityTypeBuilder<TEntity> entityTypeBuilder)
{
var expression = base.CreateFilterExpression<TEntity>(modelBuilder);
var expression = base.CreateFilterExpression<TEntity>(modelBuilder, entityTypeBuilder);
if (typeof(IIsActive).IsAssignableFrom(typeof(TEntity)))
{
@ -274,9 +274,9 @@ protected override bool ShouldFilterEntity<TEntity>(IMutableEntityType entityTyp
return base.ShouldFilterEntity<TEntity>(entityType);
}
protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>(ModelBuilder modelBuilder)
protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>(ModelBuilder modelBuilder, EntityTypeBuilder<TEntity> entityTypeBuilder)
{
var expression = base.CreateFilterExpression<TEntity>(modelBuilder);
var expression = base.CreateFilterExpression<TEntity>(modelBuilder, entityTypeBuilder);
if (typeof(IIsActive).IsAssignableFrom(typeof(TEntity)))
{
@ -294,19 +294,19 @@ protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntit
var isActive = args[0];
var boolParam = args[1];
if (abpEfCoreCurrentDbContext.Context?.DataFilter.IsEnabled<IIsActive>() == true)
if (abpEfCoreCurrentDbContext.GetRequiredContext().DataFilter.IsEnabled<IIsActive>())
{
// isActive == true
return new SqlBinaryExpression(
ExpressionType.Equal,
isActive,
new SqlConstantExpression(Expression.Constant(true), boolParam.TypeMapping),
new SqlConstantExpression(true, typeof(bool), isActive.TypeMapping ?? boolParam.TypeMapping),
boolParam.Type,
boolParam.TypeMapping);
}
// empty where sql
return new SqlConstantExpression(Expression.Constant(true), boolParam.TypeMapping);
return new SqlConstantExpression(true, typeof(bool), boolParam.TypeMapping);
});
}
@ -342,6 +342,27 @@ public override string GetCompiledQueryCacheKey()
Include any other values read at compilation time in the cache key as well. Keep the call to `base.GetCompiledQueryCacheKey()` to preserve ABP's filter-state keys.
##### Compiled queries
When user-defined function mapping is enabled, `EF.CompileQuery` and `EF.CompileAsyncQuery` cannot use the soft delete and multi-tenant filters, or your own filters that call `AbpEfCoreCurrentDbContext.GetRequiredContext()`. Queries that need these filters throw an `AbpException`. Queries that don't need them, for example with `IgnoreQueryFilters()`, are not affected.
Run these queries as normal LINQ queries, or disable user-defined function mapping:
````csharp
Configure<AbpEfCoreGlobalFilterOptions>(options =>
{
options.UseDbFunction = false;
});
````
The data filters still apply when `UseDbFunction` is `false`. Use this setting if a third-party library compiles filtered queries itself.
In custom `HasTranslation` callbacks, use `AbpEfCoreCurrentDbContext.GetRequiredContext()` instead of `Context`, as shown above.
Don't replace `ICompiledQueryCacheKeyGenerator` or `IDatabase` with `ReplaceService` while user-defined function mapping is enabled. If you need to replace either service, set `UseDbFunction` to `false` and don't add `AbpDbContextOptionsExtension` yourself.
If you build EF Core's internal service provider yourself, call `new AbpDbContextOptionsExtension().ApplyServices(services)` after registering the database provider services.
##### Make User-defined function mapping compatible with [DevExtreme.AspNet.Data's](https://github.com/DevExpress/DevExtreme.AspNet.Data) `IAsyncAdapter`
If you are using [DevExtreme.AspNet.Data](https://github.com/DevExpress/DevExtreme.AspNet.Data) and `User-defined function mapping`, You need to create a custom adapter to compatible with `IAsyncAdapter`.

23
docs/en/release-info/migration-guides/abp-10-7.md

@ -255,6 +255,29 @@ Add any other value the callback reads at compilation time to the key the same w
> See the [Data Filtering](../../framework/infrastructure/data-filtering.md) document and [#26282](https://github.com/abpframework/abp/pull/26282) for details.
### Compiled Queries with User-defined Function Mapping
**Who is affected**
- Applications that use `EF.CompileQuery` or `EF.CompileAsyncQuery` on entities with the soft delete or multi-tenant filters, while `AbpEfCoreGlobalFilterOptions.UseDbFunction` is enabled. It is enabled by default for the SQL Server, MySQL, PostgreSQL, Oracle and SQLite providers.
- Applications that use third-party libraries that compile filtered queries themselves.
- Applications with custom `HasTranslation` filters that read `AbpEfCoreCurrentDbContext.Context`.
- Applications that replace `ICompiledQueryCacheKeyGenerator` or `IDatabase` with `ReplaceService` while `UseDbFunction` is enabled.
**What changed**
- These queries could run without the soft delete and multi-tenant filters and return soft deleted rows and the rows of other tenants. They now throw an `AbpException`.
- Replacing `ICompiledQueryCacheKeyGenerator` or `IDatabase` with `ReplaceService` now throws an `AbpException`.
**What to do**
- Run filtered queries as normal LINQ queries, or set `UseDbFunction` to `false`. The data filters still apply with this setting.
- Use the new `AbpEfCoreCurrentDbContext.GetRequiredContext()` method instead of `Context` in custom `HasTranslation` callbacks.
- If you need to replace `ICompiledQueryCacheKeyGenerator` or `IDatabase`, set `UseDbFunction` to `false` and don't add `AbpDbContextOptionsExtension` yourself.
- If you build EF Core's internal service provider yourself, call `new AbpDbContextOptionsExtension().ApplyServices(services)` after registering the database provider services.
> See the [Data Filtering](../../framework/infrastructure/data-filtering.md) document and [#26284](https://github.com/abpframework/abp/pull/26284) for details.
### Dependency Updates
**Who is affected**

4
framework/src/Volo.Abp.EntityFrameworkCore/Microsoft/Extensions/DependencyInjection/AbpEfCoreModelBuilderExtensions.cs

@ -19,7 +19,7 @@ public static class AbpEfCoreModelBuilderExtensions
var isDeleted = args[0];
var boolParam = args[1];
if (abpEfCoreCurrentDbContext.Context?.DataFilter.IsEnabled<ISoftDelete>() == true)
if (abpEfCoreCurrentDbContext.GetRequiredContext().DataFilter.IsEnabled<ISoftDelete>())
{
// IsDeleted == false. Use the column's TypeMapping so any ValueConverter is applied to the literal.
return new SqlBinaryExpression(
@ -47,7 +47,7 @@ public static class AbpEfCoreModelBuilderExtensions
var currentTenantId = args[1];
var boolParam = args[2];
if (abpEfCoreCurrentDbContext.Context?.DataFilter.IsEnabled<IMultiTenant>() == true)
if (abpEfCoreCurrentDbContext.GetRequiredContext().DataFilter.IsEnabled<IMultiTenant>())
{
// TenantId == CurrentTenantId
return new SqlBinaryExpression(

28
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContextOptionsExtension.cs

@ -3,8 +3,10 @@ using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;
using Volo.Abp.EntityFrameworkCore.GlobalFilters;
namespace Volo.Abp.EntityFrameworkCore;
@ -13,23 +15,31 @@ public class AbpDbContextOptionsExtension : IDbContextOptionsExtension
{
public void ApplyServices(IServiceCollection services)
{
var serviceDescriptor = services.FirstOrDefault(x => x.ServiceType == typeof(ICompiledQueryCacheKeyGenerator));
if (serviceDescriptor != null && serviceDescriptor.ImplementationType != null)
services.Decorate<ICompiledQueryCacheKeyGenerator>((provider, inner) =>
ActivatorUtilities.CreateInstance<AbpCompiledQueryCacheKeyGenerator>(provider, inner));
// The user-defined functions are only translated by relational providers, and others, such as InMemory, cast IDatabase to their own type.
if (services.IsAdded<IRelationalConnection>())
{
services.Remove(serviceDescriptor);
services.AddScoped(serviceDescriptor.ImplementationType);
services.Add(ServiceDescriptor.Scoped<ICompiledQueryCacheKeyGenerator>(provider =>
ActivatorUtilities.CreateInstance<AbpCompiledQueryCacheKeyGenerator>(provider,
provider.GetRequiredService(serviceDescriptor.ImplementationType)
.As<ICompiledQueryCacheKeyGenerator>())));
services.Decorate<IDatabase>((provider, inner) =>
ActivatorUtilities.CreateInstance<AbpEfCoreDatabase>(provider, inner));
}
services.Replace(ServiceDescriptor.Scoped<IAsyncQueryProvider, AbpEntityQueryProvider>());
services.AddSingleton(typeof(AbpEfCoreCurrentDbContext));
services.TryAddSingleton<AbpEfCoreCurrentDbContext>();
}
public void Validate(IDbContextOptions options)
{
// EF Core applies ReplaceService after ApplyServices, so it would silently remove the wrappers.
var replacedServices = options.FindExtension<CoreOptionsExtension>()?.ReplacedServices;
if (replacedServices != null && replacedServices.Keys.Any(x => x.Item1 == typeof(ICompiledQueryCacheKeyGenerator) || x.Item1 == typeof(IDatabase)))
{
throw new AbpException(
"ICompiledQueryCacheKeyGenerator and IDatabase cannot be replaced with ReplaceService while AbpDbContextOptionsExtension is used, " +
"because ABP wraps them to apply the data filters. Remove the ReplaceService call, or set 'UseDbFunction' of 'AbpEfCoreGlobalFilterOptions' to false " +
"and don't add AbpDbContextOptionsExtension yourself.");
}
}
public DbContextOptionsExtensionInfo Info => new AbpOptionsExtensionInfo(this);

34
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpEntityQueryProvider.cs

@ -1,7 +1,10 @@
using System.Linq.Expressions;
using System.Threading;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using Volo.Abp.EntityFrameworkCore.GlobalFilters;
namespace Volo.Abp.EntityFrameworkCore;
@ -12,6 +15,8 @@ public class AbpEntityQueryProvider : EntityQueryProvider
protected AbpEfCoreCurrentDbContext AbpEfCoreCurrentDbContext { get; }
protected ICurrentDbContext CurrentDbContext { get; }
private bool _queryServicesChecked;
public AbpEntityQueryProvider(
IQueryCompiler queryCompiler,
AbpEfCoreCurrentDbContext abpEfCoreCurrentDbContext,
@ -24,7 +29,8 @@ public class AbpEntityQueryProvider : EntityQueryProvider
public override object Execute(Expression expression)
{
using (AbpEfCoreCurrentDbContext.Use(CurrentDbContext.Context as IAbpEfCoreDbFunctionContext))
CheckQueryServices();
using (AbpEfCoreCurrentDbContext.BeginQuery(CurrentDbContext.Context as IAbpEfCoreDbFunctionContext))
{
return base.Execute(expression);
}
@ -32,7 +38,8 @@ public class AbpEntityQueryProvider : EntityQueryProvider
public override TResult Execute<TResult>(Expression expression)
{
using (AbpEfCoreCurrentDbContext.Use(CurrentDbContext.Context as IAbpEfCoreDbFunctionContext))
CheckQueryServices();
using (AbpEfCoreCurrentDbContext.BeginQuery(CurrentDbContext.Context as IAbpEfCoreDbFunctionContext))
{
return base.Execute<TResult>(expression);
}
@ -40,10 +47,31 @@ public class AbpEntityQueryProvider : EntityQueryProvider
public override TResult ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken = new CancellationToken())
{
using (AbpEfCoreCurrentDbContext.Use(CurrentDbContext.Context as IAbpEfCoreDbFunctionContext))
CheckQueryServices();
using (AbpEfCoreCurrentDbContext.BeginQuery(CurrentDbContext.Context as IAbpEfCoreDbFunctionContext))
{
return base.ExecuteAsync<TResult>(expression, cancellationToken);
}
}
protected virtual void CheckQueryServices()
{
if (_queryServicesChecked)
{
return;
}
var dbContext = CurrentDbContext.Context;
if (dbContext is IAbpEfCoreDbFunctionContext abpDbContext && abpDbContext.UseDbFunction() && dbContext.Database.IsRelational() &&
(dbContext.GetService<IDatabase>() is not AbpEfCoreDatabase ||
dbContext.GetService<ICompiledQueryCacheKeyGenerator>() is not AbpCompiledQueryCacheKeyGenerator))
{
throw new AbpException(
"The data filters cannot be applied, because the EF Core services of ABP are not registered. " +
"Add AbpDbContextOptionsExtension after the database provider, or set 'UseDbFunction' of 'AbpEfCoreGlobalFilterOptions' to false.");
}
_queryServicesChecked = true;
}
}
#pragma warning restore EF1001

81
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/DependencyInjection/ServiceCollectionDecorateExtensions.cs

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

2
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/GlobalFilters/AbpCompiledQueryCacheKeyGenerator.cs

@ -39,6 +39,8 @@ public class AbpCompiledQueryCacheKeyGenerator : ICompiledQueryCacheKeyGenerator
}
}
CurrentContext.Context.GetService<AbpEfCoreCurrentDbContext>().AuthorizeQueryCompilation(abpEfCoreDbFunctionContext, query);
return new AbpCompiledQueryCacheKey(cacheKey, abpCacheKey);
}

56
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/GlobalFilters/AbpEfCoreCurrentDbContext.cs

@ -1,4 +1,5 @@
using System;
using System.Linq.Expressions;
using System.Threading;
namespace Volo.Abp.EntityFrameworkCore.GlobalFilters;
@ -6,9 +7,17 @@ namespace Volo.Abp.EntityFrameworkCore.GlobalFilters;
public class AbpEfCoreCurrentDbContext
{
private readonly AsyncLocal<IAbpEfCoreDbFunctionContext?> _current = new AsyncLocal<IAbpEfCoreDbFunctionContext?>();
private readonly AsyncLocal<QueryScope?> _queryScope = new AsyncLocal<QueryScope?>();
public IAbpEfCoreDbFunctionContext? Context => _current.Value;
public virtual IAbpEfCoreDbFunctionContext GetRequiredContext()
{
return Context ?? throw new AbpException(
"The data filters cannot be applied to a query that is compiled outside of EF Core's normal query pipeline, such as EF.CompileQuery or EF.CompileAsyncQuery. " +
"Run it as a normal LINQ query, or set 'UseDbFunction' of 'AbpEfCoreGlobalFilterOptions' to false.");
}
public IDisposable Use(IAbpEfCoreDbFunctionContext? context)
{
var previousValue = Context;
@ -18,4 +27,51 @@ public class AbpEfCoreCurrentDbContext
_current.Value = previousValue;
});
}
// Only the query of AbpEntityQueryProvider puts the filter state into the compiled query cache key, so only its compilation
// may read it. Other compilations, such as EF.CompileQuery or a query compiled while another query runs, must fail.
internal IDisposable BeginQuery(IAbpEfCoreDbFunctionContext? context)
{
var previousScope = _queryScope.Value;
_queryScope.Value = context == null ? null : new QueryScope(context);
var contextScope = Use(context);
return new DisposeAction(() =>
{
contextScope.Dispose();
_queryScope.Value = previousScope;
});
}
internal void AuthorizeQueryCompilation(IAbpEfCoreDbFunctionContext context, Expression query)
{
var scope = _queryScope.Value;
if (scope != null && scope.Context == context)
{
scope.AuthorizedQuery = query;
}
}
internal IDisposable BeginQueryCompilation(IAbpEfCoreDbFunctionContext? context, Expression query)
{
var scope = _queryScope.Value;
if (scope == null || scope.Context != context || !ReferenceEquals(scope.AuthorizedQuery, query))
{
return Use(null);
}
scope.AuthorizedQuery = null;
return Use(scope.Context);
}
private sealed class QueryScope
{
public IAbpEfCoreDbFunctionContext Context { get; }
public Expression? AuthorizedQuery { get; set; }
public QueryScope(IAbpEfCoreDbFunctionContext context)
{
Context = context;
}
}
}

56
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/GlobalFilters/AbpEfCoreDatabase.cs

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

77
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/AbpDbContextOptionsExtension_Tests.cs

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

11
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheMultiTenantRow.cs

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

11
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheSoftDeleteRow.cs

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

46
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestBase.cs

@ -154,4 +154,50 @@ public abstract class CompiledQueryCacheTestBase<TStartupModule> : TestAppTestBa
(counter.Count - before).ShouldBe(1);
await uow.CompleteAsync();
}
[Fact]
public async Task Should_Apply_Filters_To_Other_Query_Entry_Points()
{
var names = await RunInTenantAsync(CompiledQueryCacheTestModuleBase.TenantA, async db =>
{
(await db.Rows.IgnoreQueryFilters().CountAsync()).ShouldBe(CompiledQueryCacheTestModuleBase.Rows.Length);
db.Rows.Select(row => row.Name).ToQueryString().ShouldContain("IsDeleted");
(await db.Rows.Where(row => row.Name == "B-live").ExecuteUpdateAsync(s => s.SetProperty(row => row.Name, "B-updated"))).ShouldBe(0);
(await db.Rows.Where(row => row.Name == "A-live").ExecuteUpdateAsync(s => s.SetProperty(row => row.Name, "A-updated"))).ShouldBe(1);
var row = await db.Rows.SingleAsync();
row.Name = "A-saved";
await db.SaveChangesAsync();
return await db.Rows.AsNoTracking().Select(x => x.Name).ToListAsync();
});
names.ShouldBe(new[] { "A-saved" });
}
protected async Task<List<string>> RunInTenantAsync(
Guid? tenantId,
Func<CompiledQueryCacheTestDbContext, Task<List<string>>> query)
{
using var uow = GetRequiredService<IUnitOfWorkManager>().Begin();
using var tenant = GetRequiredService<ICurrentTenant>().Change(tenantId);
var context = GetRequiredService<CompiledQueryCacheTestDbContext>();
context.UseDbFunction().ShouldBe(UseDbFunction);
var names = await query(context);
await uow.CompleteAsync();
return names;
}
protected static async Task<List<string>> ToListAsync(IAsyncEnumerable<string> source)
{
var names = new List<string>();
await foreach (var name in source)
{
names.Add(name);
}
return names;
}
}

46
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestDatabase.cs

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

4
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestDbContext.cs

@ -6,6 +6,10 @@ public class CompiledQueryCacheTestDbContext : AbpDbContext<CompiledQueryCacheTe
{
public DbSet<CompiledQueryCacheTestRow> Rows { get; set; }
public DbSet<CompiledQueryCacheSoftDeleteRow> SoftDeleteRows { get; set; }
public DbSet<CompiledQueryCacheMultiTenantRow> MultiTenantRows { get; set; }
public CompiledQueryCacheTestDbContext(DbContextOptions<CompiledQueryCacheTestDbContext> options)
: base(options)
{

49
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestHooks.cs

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

59
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestModuleBase.cs

@ -1,6 +1,7 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore.GlobalFilters;
@ -29,20 +30,52 @@ public abstract class CompiledQueryCacheTestModuleBase : AbpModule
protected abstract bool UseDbFunction { get; }
protected virtual bool AddAbpServicesBeforeDatabaseProvider => false;
protected virtual bool AddCustomDatabase => false;
// When false, EF Core builds its own service provider, so it applies the ReplaceService calls of the options.
protected virtual bool UseExternalEfServiceProvider => true;
protected virtual void ConfigureEfOptions(DbContextOptionsBuilder options)
{
}
public override void ConfigureServices(ServiceConfigurationContext context)
{
var counter = new QueryCompilationCounter();
var hooks = new CompiledQueryCacheTestHooks();
var databaseRecorder = new CompiledQueryCacheTestDatabaseRecorder();
// Avoid growing EF's global service-provider cache across test applications.
var efServices = new ServiceCollection();
efServices.AddEntityFrameworkSqlite();
if (UseDbFunction)
if (UseExternalEfServiceProvider)
{
new AbpDbContextOptionsExtension().ApplyServices(efServices);
// Avoid growing EF's global service-provider cache across test applications.
var efServices = new ServiceCollection();
if (UseDbFunction && AddAbpServicesBeforeDatabaseProvider)
{
new AbpDbContextOptionsExtension().ApplyServices(efServices);
}
efServices.AddEntityFrameworkSqlite();
if (AddCustomDatabase)
{
efServices.AddSingleton(databaseRecorder);
efServices.AddScoped<IDatabase>(provider => ActivatorUtilities.CreateInstance<CompiledQueryCacheTestDatabase>(provider));
}
efServices.AddSingleton<IInterceptor>(new CompiledQueryCacheTestInterceptor(hooks));
if (UseDbFunction && !AddAbpServicesBeforeDatabaseProvider)
{
new AbpDbContextOptionsExtension().ApplyServices(efServices);
}
_efServiceProvider = efServices.BuildServiceProvider();
}
_efServiceProvider = efServices.BuildServiceProvider();
context.Services.AddSingleton(counter);
context.Services.AddSingleton(hooks);
context.Services.AddSingleton(databaseRecorder);
context.Services.AddTransient<IAbpEfCoreCompiledQueryCacheKeyProvider>(_ => new CompiledQueryCacheTestKeyProvider(hooks));
context.Services.AddAbpDbContext<CompiledQueryCacheTestDbContext>();
Configure<AbpEfCoreGlobalFilterOptions>(options => options.UseDbFunction = UseDbFunction);
Configure<AbpDbConnectionOptions>(options => options.ConnectionStrings.Default = _database.ConnectionString);
@ -50,7 +83,17 @@ public abstract class CompiledQueryCacheTestModuleBase : AbpModule
{
configuration.UseSqlite();
configuration.DbContextOptions.UseLoggerFactory(null);
configuration.DbContextOptions.UseInternalServiceProvider(_efServiceProvider);
if (UseExternalEfServiceProvider)
{
configuration.DbContextOptions.UseInternalServiceProvider(_efServiceProvider);
}
else
{
configuration.DbContextOptions.EnableServiceProviderCaching(false);
configuration.DbContextOptions.AddInterceptors(new CompiledQueryCacheTestInterceptor(hooks));
}
ConfigureEfOptions(configuration.DbContextOptions);
configuration.DbContextOptions.LogTo(
_ => counter.Increment(),
new[] { CoreEventId.QueryCompilationStarting });
@ -74,6 +117,6 @@ public abstract class CompiledQueryCacheTestModuleBase : AbpModule
public override void OnApplicationShutdown(ApplicationShutdownContext context)
{
_database.Dispose();
_efServiceProvider.Dispose();
_efServiceProvider?.Dispose();
}
}

13
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestModuleWithAbpServicesFirst.cs

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

13
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestModuleWithDatabaseFactory.cs

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

43
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestModuleWithQueryCompiler.cs

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

56
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCacheTestQueryCompiler.cs

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

25
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCache_AbpServicesFirst_Tests.cs

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

49
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCache_DatabaseFactory_Tests.cs

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

75
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCache_QueryCompiler_Tests.cs

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

277
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCache_Tests.cs

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

52
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/CompiledQueryCache/CompiledQueryCache_WithoutDbFunction_Tests.cs

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

160
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DependencyInjection/ServiceCollectionDecorateExtensions_Tests.cs

@ -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…
Cancel
Save