mirror of https://github.com/abpframework/abp.git
22 changed files with 3452 additions and 46 deletions
@ -0,0 +1,276 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Reflection; |
|||
using System.Runtime.CompilerServices; |
|||
using Autofac.Core; |
|||
using Autofac.Core.Resolving.Pipeline; |
|||
using Autofac.Extras.DynamicProxy; |
|||
using Castle.DynamicProxy; |
|||
using Volo.Abp; |
|||
using Volo.Abp.Autofac; |
|||
|
|||
namespace Autofac.Builder; |
|||
|
|||
/// <summary>
|
|||
/// The class and interface interception of Autofac.Extras.DynamicProxy, generating proxies with
|
|||
/// <see cref="ProxyGenerator"/> instead of the single static generator that package keeps for the whole process.
|
|||
/// Interceptors are read from the same registration metadata as Autofac's, so <c>InterceptedBy</c> and
|
|||
/// <see cref="InterceptAttribute"/> keep working. It follows Autofac.Extras.DynamicProxy 7.1.0, whose metadata keys it
|
|||
/// reads; check it again when that package is upgraded.
|
|||
/// </summary>
|
|||
public static class AbpInterceptionRegistrationExtensions |
|||
{ |
|||
// Autofac.Extras.DynamicProxy's metadata keys, written by its InterceptedBy.
|
|||
private const string InterceptorsPropertyName = "Autofac.Extras.DynamicProxy.RegistrationExtensions.InterceptorsPropertyName"; |
|||
private const string AttributeInterceptorsPropertyName = "Autofac.Extras.DynamicProxy.RegistrationExtensions.AttributeInterceptorsPropertyName"; |
|||
|
|||
private static readonly object SyncRoot = new(); |
|||
private static int _shardCount = 16; |
|||
private static volatile ProxyGenerator? _proxyGenerator; |
|||
|
|||
/// <summary>
|
|||
/// How many dynamic modules proxies are spread over. It is read when <see cref="ProxyGenerator"/> is first used,
|
|||
/// which happens while the container is built, and cannot change after that, because a key must keep its shard.
|
|||
/// Defaults to 16.
|
|||
/// </summary>
|
|||
public static int ShardCount |
|||
{ |
|||
get |
|||
{ |
|||
lock (SyncRoot) |
|||
{ |
|||
return _shardCount; |
|||
} |
|||
} |
|||
set |
|||
{ |
|||
Check.Positive(value, nameof(value)); |
|||
lock (SyncRoot) |
|||
{ |
|||
if (_proxyGenerator != null && value != _shardCount) |
|||
{ |
|||
throw new AbpException("The proxy shard count cannot change once the proxy generator has been created."); |
|||
} |
|||
|
|||
_shardCount = value; |
|||
} |
|||
} |
|||
} |
|||
|
|||
public static ProxyGenerator ProxyGenerator |
|||
{ |
|||
get |
|||
{ |
|||
var generator = _proxyGenerator; |
|||
if (generator != null) |
|||
{ |
|||
return generator; |
|||
} |
|||
|
|||
lock (SyncRoot) |
|||
{ |
|||
return _proxyGenerator ??= new ProxyGenerator(new AbpShardedProxyBuilder(_shardCount)); |
|||
} |
|||
} |
|||
} |
|||
|
|||
public static IRegistrationBuilder<TLimit, TConcreteReflectionActivatorData, TRegistrationStyle> EnableAbpClassInterceptors<TLimit, TConcreteReflectionActivatorData, TRegistrationStyle>( |
|||
this IRegistrationBuilder<TLimit, TConcreteReflectionActivatorData, TRegistrationStyle> registration, |
|||
ProxyGenerationOptions? options = null) |
|||
where TConcreteReflectionActivatorData : ConcreteReflectionActivatorData |
|||
{ |
|||
Check.NotNull(registration, nameof(registration)); |
|||
|
|||
options ??= ProxyGenerationOptions.Default; |
|||
registration.ActivatorData.ImplementationType = ProxyGenerator.ProxyBuilder.CreateClassProxyType( |
|||
registration.ActivatorData.ImplementationType, |
|||
Type.EmptyTypes, |
|||
options); |
|||
|
|||
var interceptorServices = GetInterceptorServicesFromAttributes(registration.ActivatorData.ImplementationType); |
|||
AddInterceptorServicesToMetadata(registration, interceptorServices, AttributeInterceptorsPropertyName); |
|||
|
|||
// The proxy's constructor takes the options' mixins, then the interceptors, then the options' selector.
|
|||
registration.OnPreparing(e => |
|||
{ |
|||
var proxyParameters = new List<Parameter>(); |
|||
var index = 0; |
|||
|
|||
if (options.HasMixins) |
|||
{ |
|||
foreach (var mixin in options.MixinData.Mixins) |
|||
{ |
|||
proxyParameters.Add(new PositionalParameter(index++, mixin)); |
|||
} |
|||
} |
|||
|
|||
proxyParameters.Add(new PositionalParameter(index++, GetInterceptorServices(e.Component, registration.ActivatorData.ImplementationType) |
|||
.Select(s => e.Context.ResolveService(s)) |
|||
.Cast<IInterceptor>() |
|||
.ToArray())); |
|||
|
|||
if (options.Selector != null) |
|||
{ |
|||
proxyParameters.Add(new PositionalParameter(index, options.Selector)); |
|||
} |
|||
|
|||
e.Parameters = proxyParameters.Concat(e.Parameters).ToArray(); |
|||
}); |
|||
|
|||
return registration; |
|||
} |
|||
|
|||
public static IRegistrationBuilder<TLimit, TActivatorData, TSingleRegistrationStyle> EnableAbpInterfaceInterceptors<TLimit, TActivatorData, TSingleRegistrationStyle>( |
|||
this IRegistrationBuilder<TLimit, TActivatorData, TSingleRegistrationStyle> registration, |
|||
ProxyGenerationOptions? options = null) |
|||
{ |
|||
Check.NotNull(registration, nameof(registration)); |
|||
|
|||
registration.ConfigurePipeline(p => p.Use(PipelinePhase.Activation, MiddlewareInsertionMode.StartOfPhase, (ctx, next) => |
|||
{ |
|||
next(ctx); |
|||
|
|||
EnsureInterfaceInterceptionApplies(ctx.Registration); |
|||
|
|||
var proxiedInterfaces = ProxiedInterfaces.GetValue(ctx.Instance!.GetType(), static type => new ProxiedInterfaceSet(type)); |
|||
if (proxiedInterfaces.Primary == null) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
var theInterface = proxiedInterfaces.Primary; |
|||
var interfaces = proxiedInterfaces.Additional; |
|||
|
|||
var interceptors = GetInterceptorServices(ctx.Registration, ctx.Instance.GetType()) |
|||
.Select(s => ctx.ResolveService(s)) |
|||
.Cast<IInterceptor>() |
|||
.ToArray(); |
|||
|
|||
ctx.Instance = options == null |
|||
? ProxyGenerator.CreateInterfaceProxyWithTarget(theInterface, interfaces, ctx.Instance, interceptors) |
|||
: ProxyGenerator.CreateInterfaceProxyWithTarget(theInterface, interfaces, ctx.Instance, options, interceptors); |
|||
})); |
|||
|
|||
return registration; |
|||
} |
|||
|
|||
private static readonly ConditionalWeakTable<Type, ProxiedInterfaceSet> ProxiedInterfaces = new(); |
|||
|
|||
/// <summary>
|
|||
/// The interfaces an interface proxy of a type implements, worked out once per type.
|
|||
/// </summary>
|
|||
/// <remarks>
|
|||
/// The proxy implements the same interfaces whichever comes first, but Castle names it after the first one and copies
|
|||
/// some of that one's attributes to the proxy type. Preferring the class's own I{ClassName} interface gives most
|
|||
/// proxies a name of their own instead of one shared by every implementation of a common interface, which keeps them
|
|||
/// spread over the proxy builder's modules. It is only preferred when neither interface has a public attribute other
|
|||
/// than the compiler's nullable annotations, so the proxy type's attributes stay as they were whatever Castle is
|
|||
/// configured to copy.
|
|||
/// </remarks>
|
|||
private sealed class ProxiedInterfaceSet |
|||
{ |
|||
public Type? Primary { get; } |
|||
|
|||
public Type[] Additional { get; } |
|||
|
|||
public ProxiedInterfaceSet(Type type) |
|||
{ |
|||
var interfaces = type.GetInterfaces().Where(ProxyUtil.IsAccessible).ToArray(); |
|||
if (interfaces.Length == 0) |
|||
{ |
|||
Additional = Type.EmptyTypes; |
|||
return; |
|||
} |
|||
|
|||
var primary = interfaces[0]; |
|||
var own = interfaces.FirstOrDefault(i => i.Name == "I" + type.Name); |
|||
if (own != null && own != primary && !HasPublicAttributes(primary) && !HasPublicAttributes(own)) |
|||
{ |
|||
primary = own; |
|||
} |
|||
|
|||
Primary = primary; |
|||
Additional = interfaces.Where(i => i != primary).ToArray(); |
|||
} |
|||
|
|||
// The compiler's nullable annotations are public on .NET but say nothing a caller reads off a proxy type;
|
|||
// counting them would keep nearly every interface of a nullable-enabled project in place.
|
|||
private static readonly string[] NullableAnnotations = |
|||
{ |
|||
"System.Runtime.CompilerServices.NullableAttribute", |
|||
"System.Runtime.CompilerServices.NullableContextAttribute", |
|||
"System.Runtime.CompilerServices.NullablePublicOnlyAttribute" |
|||
}; |
|||
|
|||
private static bool HasPublicAttributes(Type interfaceType) |
|||
{ |
|||
return interfaceType.CustomAttributes.Any(attribute => |
|||
(attribute.AttributeType.IsPublic || attribute.AttributeType.IsNestedPublic) && |
|||
!NullableAnnotations.Contains(attribute.AttributeType.FullName)); |
|||
} |
|||
} |
|||
|
|||
private static void EnsureInterfaceInterceptionApplies(IComponentRegistration componentRegistration) |
|||
{ |
|||
if (componentRegistration.Services |
|||
.OfType<IServiceWithType>() |
|||
.Any(s => !s.ServiceType.GetTypeInfo().IsInterface || !ProxyUtil.IsAccessible(s.ServiceType))) |
|||
{ |
|||
throw new InvalidOperationException( |
|||
$"The component {componentRegistration} cannot use interface interception as it provides services that are not publicly visible interfaces."); |
|||
} |
|||
} |
|||
|
|||
private static void AddInterceptorServicesToMetadata<TLimit, TActivatorData, TStyle>( |
|||
IRegistrationBuilder<TLimit, TActivatorData, TStyle> builder, |
|||
IEnumerable<Service> interceptorServices, |
|||
string metadataKey) |
|||
{ |
|||
if (builder.RegistrationData.Metadata.TryGetValue(metadataKey, out var existing) && existing is IEnumerable<Service> existingServices) |
|||
{ |
|||
builder.RegistrationData.Metadata[metadataKey] = existingServices.Concat(interceptorServices).Distinct(); |
|||
} |
|||
else |
|||
{ |
|||
builder.RegistrationData.Metadata.Add(metadataKey, interceptorServices); |
|||
} |
|||
} |
|||
|
|||
private static IEnumerable<Service> GetInterceptorServices(IComponentRegistration registration, Type implType) |
|||
{ |
|||
var result = Enumerable.Empty<Service>(); |
|||
|
|||
if (registration.Metadata.TryGetValue(InterceptorsPropertyName, out var services) && services is IEnumerable<Service> existingPropertyServices) |
|||
{ |
|||
result = result.Concat(existingPropertyServices); |
|||
} |
|||
|
|||
return registration.Metadata.TryGetValue(AttributeInterceptorsPropertyName, out services) && services is IEnumerable<Service> existingAttributeServices |
|||
? result.Concat(existingAttributeServices) |
|||
: result.Concat(GetInterceptorServicesFromAttributes(implType)); |
|||
} |
|||
|
|||
private static IEnumerable<Service> GetInterceptorServicesFromAttributes(Type implType) |
|||
{ |
|||
var implTypeInfo = implType.GetTypeInfo(); |
|||
if (!implTypeInfo.IsClass) |
|||
{ |
|||
return Enumerable.Empty<Service>(); |
|||
} |
|||
|
|||
var classAttributeServices = implTypeInfo |
|||
.GetCustomAttributes(typeof(InterceptAttribute), true) |
|||
.Cast<InterceptAttribute>() |
|||
.Select(att => att.InterceptorService); |
|||
|
|||
var interfaceAttributeServices = implType |
|||
.GetInterfaces() |
|||
.SelectMany(i => i.GetTypeInfo().GetCustomAttributes(typeof(InterceptAttribute), true)) |
|||
.Cast<InterceptAttribute>() |
|||
.Select(att => att.InterceptorService); |
|||
|
|||
return classAttributeServices.Concat(interfaceAttributeServices); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,76 @@ |
|||
using System; |
|||
using Castle.Core.Logging; |
|||
using Castle.DynamicProxy; |
|||
|
|||
namespace Volo.Abp.Autofac; |
|||
|
|||
/// <summary>
|
|||
/// Spreads proxy types over several dynamic modules. Generating a type gets slower as its dynamic module grows, so
|
|||
/// keeping every proxy of an application in one module makes generating them all grow quadratically with their
|
|||
/// number. A proxy is routed by the simple name of the type it proxies: Castle names a proxy after that name and keeps
|
|||
/// names unique only within one module, so types sharing a name must share a shard, or two proxies could get the
|
|||
/// same full name, which code that caches by a runtime type name relies on. A key therefore always lands in the same
|
|||
/// shard, and is generated and cached there once.
|
|||
/// </summary>
|
|||
public class AbpShardedProxyBuilder : IProxyBuilder |
|||
{ |
|||
private readonly DefaultProxyBuilder[] _shards; |
|||
|
|||
public AbpShardedProxyBuilder(int shardCount) |
|||
{ |
|||
Check.Positive(shardCount, nameof(shardCount)); |
|||
|
|||
_shards = new DefaultProxyBuilder[shardCount]; |
|||
for (var i = 0; i < shardCount; i++) |
|||
{ |
|||
_shards[i] = new DefaultProxyBuilder(); |
|||
} |
|||
} |
|||
|
|||
public int ShardCount => _shards.Length; |
|||
|
|||
public ILogger Logger |
|||
{ |
|||
get => _shards[0].Logger; |
|||
set |
|||
{ |
|||
foreach (var shard in _shards) |
|||
{ |
|||
shard.Logger = value; |
|||
} |
|||
} |
|||
} |
|||
|
|||
/// <summary>The first shard's scope. Proxy generation does not read it; it exists for <see cref="IProxyBuilder"/>.</summary>
|
|||
public ModuleScope ModuleScope => _shards[0].ModuleScope; |
|||
|
|||
public Type CreateClassProxyType(Type classToProxy, Type[]? additionalInterfacesToProxy, ProxyGenerationOptions options) |
|||
{ |
|||
return ShardFor(classToProxy).CreateClassProxyType(classToProxy, additionalInterfacesToProxy, options); |
|||
} |
|||
|
|||
public Type CreateClassProxyTypeWithTarget(Type classToProxy, Type[]? additionalInterfacesToProxy, ProxyGenerationOptions options) |
|||
{ |
|||
return ShardFor(classToProxy).CreateClassProxyTypeWithTarget(classToProxy, additionalInterfacesToProxy, options); |
|||
} |
|||
|
|||
public Type CreateInterfaceProxyTypeWithTarget(Type interfaceToProxy, Type[]? additionalInterfacesToProxy, Type targetType, ProxyGenerationOptions options) |
|||
{ |
|||
return ShardFor(interfaceToProxy).CreateInterfaceProxyTypeWithTarget(interfaceToProxy, additionalInterfacesToProxy, targetType, options); |
|||
} |
|||
|
|||
public Type CreateInterfaceProxyTypeWithTargetInterface(Type interfaceToProxy, Type[]? additionalInterfacesToProxy, ProxyGenerationOptions options) |
|||
{ |
|||
return ShardFor(interfaceToProxy).CreateInterfaceProxyTypeWithTargetInterface(interfaceToProxy, additionalInterfacesToProxy, options); |
|||
} |
|||
|
|||
public Type CreateInterfaceProxyTypeWithoutTarget(Type interfaceToProxy, Type[]? additionalInterfacesToProxy, ProxyGenerationOptions options) |
|||
{ |
|||
return ShardFor(interfaceToProxy).CreateInterfaceProxyTypeWithoutTarget(interfaceToProxy, additionalInterfacesToProxy, options); |
|||
} |
|||
|
|||
private DefaultProxyBuilder ShardFor(Type proxiedType) |
|||
{ |
|||
return _shards[(StringComparer.Ordinal.GetHashCode(proxiedType.Name) & int.MaxValue) % _shards.Length]; |
|||
} |
|||
} |
|||
@ -0,0 +1,45 @@ |
|||
using System; |
|||
using System.Linq; |
|||
using Autofac.Core; |
|||
using Autofac.Core.Activators.Reflection; |
|||
using Autofac.Extensions.DependencyInjection; |
|||
using Volo.Abp.DependencyInjection; |
|||
|
|||
namespace Volo.Abp.Autofac; |
|||
|
|||
public class AutofacServiceImplementationTypeProvider : IServiceImplementationTypeProvider, ITransientDependency |
|||
{ |
|||
protected IServiceProvider ServiceProvider { get; } |
|||
|
|||
public AutofacServiceImplementationTypeProvider(IServiceProvider serviceProvider) |
|||
{ |
|||
ServiceProvider = serviceProvider; |
|||
} |
|||
|
|||
public virtual Type? GetImplementationTypeOrNull(Type serviceType) |
|||
{ |
|||
if (ServiceProvider is not AutofacServiceProvider autofacServiceProvider) |
|||
{ |
|||
return null; |
|||
} |
|||
|
|||
var registry = autofacServiceProvider.LifetimeScope.ComponentRegistry; |
|||
var service = new TypedService(serviceType); |
|||
if (!registry.TryGetServiceRegistration(service, out var serviceRegistration)) |
|||
{ |
|||
return null; |
|||
} |
|||
|
|||
// A decorator or other service middleware may return another object than the registration creates.
|
|||
if (registry.ServiceMiddlewareFor(service).Any()) |
|||
{ |
|||
return null; |
|||
} |
|||
|
|||
// The reflection activator always creates its type (a class proxy, when the service is intercepted);
|
|||
// a delegate may create any type.
|
|||
return serviceRegistration.Registration.Activator is ReflectionActivator activator |
|||
? activator.LimitType |
|||
: null; |
|||
} |
|||
} |
|||
@ -0,0 +1,13 @@ |
|||
using System; |
|||
|
|||
namespace Volo.Abp.DependencyInjection; |
|||
|
|||
public interface IServiceImplementationTypeProvider |
|||
{ |
|||
/// <summary>
|
|||
/// Gets the type of every instance the container creates for <paramref name="serviceType"/>, without creating one.
|
|||
/// Returns null when the registration does not fix the type (such as a factory method or a decorator) or the
|
|||
/// container can not tell it.
|
|||
/// </summary>
|
|||
Type? GetImplementationTypeOrNull(Type serviceType); |
|||
} |
|||
@ -0,0 +1,12 @@ |
|||
using System; |
|||
|
|||
namespace Volo.Abp.DependencyInjection; |
|||
|
|||
[Dependency(TryRegister = true)] |
|||
public class NullServiceImplementationTypeProvider : IServiceImplementationTypeProvider, ITransientDependency |
|||
{ |
|||
public Type? GetImplementationTypeOrNull(Type serviceType) |
|||
{ |
|||
return null; |
|||
} |
|||
} |
|||
@ -0,0 +1,138 @@ |
|||
using System.Threading.Tasks; |
|||
using Autofac; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.DynamicProxy; |
|||
using Volo.Abp.Testing; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Autofac; |
|||
|
|||
public class AutofacServiceImplementationTypeProvider_Tests : AbpIntegratedTest<AutofacTestModule> |
|||
{ |
|||
protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options) |
|||
{ |
|||
options.UseAutofac(); |
|||
} |
|||
|
|||
protected override void AfterAddApplication(IServiceCollection services) |
|||
{ |
|||
services.AddTransient<TypeProviderInterceptor>(); |
|||
services.AddTransient<TypeProviderInterceptedService>(); |
|||
services.OnRegistered(context => |
|||
{ |
|||
if (context.ImplementationType == typeof(TypeProviderInterceptedService)) |
|||
{ |
|||
context.Interceptors.TryAdd<TypeProviderInterceptor>(); |
|||
} |
|||
}); |
|||
|
|||
var builder = services.GetObject<ContainerBuilder>(); |
|||
builder.RegisterType<TypeProviderService>(); |
|||
builder.RegisterType<TypeProviderReplacement>().As<TypeProviderReplaced>(); |
|||
builder.Register(_ => new TypeProviderService()).As<TypeProviderCreatedByMethod>(); |
|||
builder.RegisterType<TypeProviderService>().As<ITypeProviderService>(); |
|||
builder.RegisterType<TypeProviderService>().As<ITypeProviderDecoratedService>(); |
|||
builder.RegisterDecorator<TypeProviderDecorator, ITypeProviderDecoratedService>(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Replace_The_Null_Provider() |
|||
{ |
|||
GetRequiredService<IServiceImplementationTypeProvider>().ShouldBeOfType<AutofacServiceImplementationTypeProvider>(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Tell_The_Type_A_Registration_Creates() |
|||
{ |
|||
var provider = GetRequiredService<IServiceImplementationTypeProvider>(); |
|||
|
|||
provider.GetImplementationTypeOrNull(typeof(TypeProviderService)).ShouldBe(typeof(TypeProviderService)); |
|||
provider.GetImplementationTypeOrNull(typeof(ITypeProviderService)).ShouldBe(typeof(TypeProviderService)); |
|||
provider.GetImplementationTypeOrNull(typeof(TypeProviderReplaced)).ShouldBe(typeof(TypeProviderReplacement)); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Tell_The_Proxy_Type_Of_An_Intercepted_Class() |
|||
{ |
|||
var type = GetRequiredService<IServiceImplementationTypeProvider>().GetImplementationTypeOrNull(typeof(TypeProviderInterceptedService)); |
|||
|
|||
type.ShouldNotBeNull(); |
|||
type.ShouldNotBe(typeof(TypeProviderInterceptedService)); |
|||
type.ShouldBe(GetRequiredService<TypeProviderInterceptedService>().GetType()); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Not_Tell_A_Type_It_Can_Not_Know() |
|||
{ |
|||
var provider = GetRequiredService<IServiceImplementationTypeProvider>(); |
|||
|
|||
provider.GetImplementationTypeOrNull(typeof(TypeProviderCreatedByMethod)).ShouldBeNull(); |
|||
provider.GetImplementationTypeOrNull(typeof(ITypeProviderDecoratedService)).ShouldBeNull(); |
|||
provider.GetImplementationTypeOrNull(typeof(TypeProviderNotRegistered)).ShouldBeNull(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Not_Tell_A_Type_For_Another_Container() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
services.AddTransient<TypeProviderService>(); |
|||
using var serviceProvider = services.BuildServiceProvider(); |
|||
|
|||
new AutofacServiceImplementationTypeProvider(serviceProvider) |
|||
.GetImplementationTypeOrNull(typeof(TypeProviderService)) |
|||
.ShouldBeNull(); |
|||
} |
|||
|
|||
public interface ITypeProviderService |
|||
{ |
|||
} |
|||
|
|||
public interface ITypeProviderDecoratedService |
|||
{ |
|||
} |
|||
|
|||
public class TypeProviderService : TypeProviderCreatedByMethod, ITypeProviderService, ITypeProviderDecoratedService |
|||
{ |
|||
} |
|||
|
|||
public class TypeProviderCreatedByMethod |
|||
{ |
|||
} |
|||
|
|||
public class TypeProviderReplaced |
|||
{ |
|||
} |
|||
|
|||
public class TypeProviderReplacement : TypeProviderReplaced |
|||
{ |
|||
} |
|||
|
|||
public class TypeProviderNotRegistered |
|||
{ |
|||
} |
|||
|
|||
public class TypeProviderDecorator : ITypeProviderDecoratedService |
|||
{ |
|||
public TypeProviderDecorator(ITypeProviderDecoratedService inner) |
|||
{ |
|||
} |
|||
} |
|||
|
|||
public class TypeProviderInterceptedService |
|||
{ |
|||
public virtual Task DoItAsync() |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
public class TypeProviderInterceptor : AbpInterceptor |
|||
{ |
|||
public override Task InterceptAsync(IAbpMethodInvocation invocation) |
|||
{ |
|||
return invocation.ProceedAsync(); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,725 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Reflection; |
|||
using System.Threading.Tasks; |
|||
using Autofac; |
|||
using Autofac.Builder; |
|||
using Autofac.Extras.DynamicProxy; |
|||
using Castle.DynamicProxy; |
|||
using Shouldly; |
|||
using Volo.Abp; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Autofac.Interception; |
|||
|
|||
public class AbpShardedProxy_Tests |
|||
{ |
|||
[Theory] |
|||
[InlineData(1)] |
|||
[InlineData(16)] |
|||
public void The_Same_Key_Should_Get_The_Same_Proxy_Type(int shardCount) |
|||
{ |
|||
var builder = new AbpShardedProxyBuilder(shardCount); |
|||
|
|||
var proxyType = builder.CreateClassProxyType(typeof(Calculator), Type.EmptyTypes, ProxyGenerationOptions.Default); |
|||
|
|||
builder.CreateClassProxyType(typeof(Calculator), Type.EmptyTypes, ProxyGenerationOptions.Default).ShouldBeSameAs(proxyType); |
|||
builder.CreateClassProxyType(typeof(Calculator), new[] { typeof(IExtra) }, ProxyGenerationOptions.Default).ShouldNotBeSameAs(proxyType); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Interface_Proxy_Keys_Should_Be_Reused_And_Kept_Apart() |
|||
{ |
|||
var builder = new AbpShardedProxyBuilder(16); |
|||
var options = ProxyGenerationOptions.Default; |
|||
|
|||
var withTarget = builder.CreateInterfaceProxyTypeWithTarget(typeof(ICalculator), Type.EmptyTypes, typeof(Calculator), options); |
|||
builder.CreateInterfaceProxyTypeWithTarget(typeof(ICalculator), Type.EmptyTypes, typeof(Calculator), options).ShouldBeSameAs(withTarget); |
|||
builder.CreateInterfaceProxyTypeWithTarget(typeof(ICalculator), new[] { typeof(IExtra) }, typeof(Calculator), options).ShouldNotBeSameAs(withTarget); |
|||
|
|||
var withTargetInterface = builder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ICalculator), Type.EmptyTypes, options); |
|||
builder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ICalculator), Type.EmptyTypes, options).ShouldBeSameAs(withTargetInterface); |
|||
|
|||
var withoutTarget = builder.CreateInterfaceProxyTypeWithoutTarget(typeof(ICalculator), Type.EmptyTypes, options); |
|||
builder.CreateInterfaceProxyTypeWithoutTarget(typeof(ICalculator), Type.EmptyTypes, options).ShouldBeSameAs(withoutTarget); |
|||
|
|||
new[] { withTarget, withTargetInterface, withoutTarget }.Select(proxyType => proxyType.FullName).Distinct().Count().ShouldBe(3); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Concurrent_First_Requests_Should_Get_One_Proxy_Type_Per_Key() |
|||
{ |
|||
var builder = new AbpShardedProxyBuilder(4); |
|||
var targets = DistinctlyNamedTypes(); |
|||
|
|||
var results = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(() => |
|||
targets.Select(target => builder.CreateClassProxyType(target, Type.EmptyTypes, ProxyGenerationOptions.Default)).ToArray()))); |
|||
|
|||
for (var i = 0; i < targets.Length; i++) |
|||
{ |
|||
results.Select(result => result[i]).Distinct().ShouldHaveSingleItem(); |
|||
} |
|||
|
|||
results[0].Select(proxyType => proxyType.Module).Distinct().Count().ShouldBeGreaterThan(1); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Proxies_Of_Types_Sharing_A_Simple_Name_Should_Get_Distinct_Names() |
|||
{ |
|||
var builder = new AbpShardedProxyBuilder(16); |
|||
var targets = SameNamedTypes().Concat(new[] { typeof(FirstOwner.Handler), typeof(SecondOwner.Handler) }).ToArray(); |
|||
|
|||
var proxyTypes = targets |
|||
.Select(target => builder.CreateClassProxyType(target, Type.EmptyTypes, ProxyGenerationOptions.Default)) |
|||
.ToArray(); |
|||
|
|||
proxyTypes.Select(proxyType => proxyType.FullName).Distinct().Count().ShouldBe(targets.Length); |
|||
proxyTypes.Select(proxyType => proxyType.AssemblyQualifiedName).Distinct().Count().ShouldBe(targets.Length); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Interface_Proxies_Of_One_Interface_With_Different_Targets_Should_Get_Distinct_Names() |
|||
{ |
|||
var builder = new AbpShardedProxyBuilder(16); |
|||
var targets = CalculatorTargets(); |
|||
|
|||
var proxyTypes = targets |
|||
.Select(target => builder.CreateInterfaceProxyTypeWithTarget(typeof(ICalculator), Type.EmptyTypes, target, ProxyGenerationOptions.Default)) |
|||
.ToArray(); |
|||
|
|||
proxyTypes.Distinct().Count().ShouldBe(targets.Length); |
|||
proxyTypes.Select(proxyType => proxyType.FullName).Distinct().Count().ShouldBe(targets.Length); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Interface_Interception_Should_Name_The_Proxy_After_The_Class_Own_Interface() |
|||
{ |
|||
using var container = Build(builder => builder.RegisterType<OwnInterfaceCalculator>() |
|||
.As<IOwnInterfaceCalculator>() |
|||
.As<IExtra>() |
|||
.EnableAbpInterfaceInterceptors() |
|||
.InterceptedBy(typeof(RecordingInterceptor))); |
|||
|
|||
var calculator = container.Resolve<IOwnInterfaceCalculator>(); |
|||
|
|||
calculator.GetType().FullName.ShouldStartWith("Castle.Proxies.IOwnInterfaceCalculatorProxy"); |
|||
calculator.Add(1, 2).ShouldBe(3); |
|||
((IExtra)calculator).Seven().ShouldBe(7); |
|||
container.Resolve<RecordingInterceptor>().Calls.ShouldBe(new[] { "counted:Add", "counted:Seven" }); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Interface_Interception_Should_Keep_The_Attributes_Autofac_Copies_To_The_Proxy() |
|||
{ |
|||
using var container = Build(builder => |
|||
{ |
|||
builder.RegisterType<TaggedCalculator>().Keyed<ITaggedCalculator>("autofac") |
|||
.EnableInterfaceInterceptors().InterceptedBy(typeof(RecordingInterceptor)); |
|||
builder.RegisterType<TaggedCalculator>().Keyed<ITaggedCalculator>("abp") |
|||
.EnableAbpInterfaceInterceptors().InterceptedBy(typeof(RecordingInterceptor)); |
|||
}); |
|||
|
|||
// The class's own interface is not the first one, and the first one has an attribute Castle copies.
|
|||
typeof(TaggedCalculator).GetInterfaces().First().ShouldBe(typeof(ITaggedExtra)); |
|||
var fromAutofac = container.ResolveKeyed<ITaggedCalculator>("autofac").GetType(); |
|||
var fromAbp = container.ResolveKeyed<ITaggedCalculator>("abp").GetType(); |
|||
|
|||
fromAutofac.GetCustomAttribute<ProxyTagAttribute>().ShouldNotBeNull().Tag.ShouldBe("extra"); |
|||
fromAbp.GetCustomAttribute<ProxyTagAttribute>().ShouldNotBeNull().Tag.ShouldBe("extra"); |
|||
fromAbp.GetInterfaces().OrderBy(i => i.FullName).ShouldBe(fromAutofac.GetInterfaces().OrderBy(i => i.FullName)); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Interface_Interception_Should_Keep_The_Attributes_Castle_Is_Told_To_Copy_To_The_Proxy() |
|||
{ |
|||
global::Castle.DynamicProxy.Generators.AttributesToAlwaysReplicate.Add(typeof(InheritedProxyTagAttribute)); |
|||
using var container = Build(builder => |
|||
{ |
|||
builder.RegisterType<ReplicatedCalculator>().Keyed<IReplicatedCalculator>("autofac") |
|||
.EnableInterfaceInterceptors().InterceptedBy(typeof(RecordingInterceptor)); |
|||
builder.RegisterType<ReplicatedCalculator>().Keyed<IReplicatedCalculator>("abp") |
|||
.EnableAbpInterfaceInterceptors().InterceptedBy(typeof(RecordingInterceptor)); |
|||
}); |
|||
|
|||
typeof(ReplicatedCalculator).GetInterfaces().First().ShouldBe(typeof(IReplicatedExtra)); |
|||
var fromAutofac = container.ResolveKeyed<IReplicatedCalculator>("autofac").GetType(); |
|||
var fromAbp = container.ResolveKeyed<IReplicatedCalculator>("abp").GetType(); |
|||
|
|||
fromAutofac.GetCustomAttribute<InheritedProxyTagAttribute>().ShouldNotBeNull().Tag.ShouldBe("replicated"); |
|||
fromAbp.GetCustomAttribute<InheritedProxyTagAttribute>().ShouldNotBeNull().Tag.ShouldBe("replicated"); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Properties_Should_Be_Set_On_Same_Named_Proxies_From_Different_Generators() |
|||
{ |
|||
// Two generators name a proxy of the same interface the same way, as Autofac's own and ABP's do side by side.
|
|||
var first = (IPropertyTarget)new ProxyGenerator(new DefaultProxyBuilder()) |
|||
.CreateInterfaceProxyWithTarget(typeof(IPropertyTarget), new PropertyTarget01()); |
|||
var second = (IPropertyTarget)new ProxyGenerator(new DefaultProxyBuilder()) |
|||
.CreateInterfaceProxyWithTarget(typeof(IPropertyTarget), new PropertyTarget02()); |
|||
first.GetType().FullName.ShouldBe(second.GetType().FullName); |
|||
first.GetType().ShouldNotBe(second.GetType()); |
|||
|
|||
ObjectHelper.TrySetProperty(first, x => x.Value, () => 7); |
|||
ObjectHelper.TrySetProperty(second, x => x.Value, () => 42); |
|||
|
|||
((IPropertyTarget)ProxyUtil.GetUnproxiedInstance(first)).Value.ShouldBe(7); |
|||
((IPropertyTarget)ProxyUtil.GetUnproxiedInstance(second)).Value.ShouldBe(42); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Interface_Interception_Should_Name_The_Proxy_After_A_Nullable_Annotated_Own_Interface() |
|||
{ |
|||
using var container = Build(builder => builder.RegisterType<NullableCalculator>() |
|||
.As<INullableCalculator>() |
|||
.EnableAbpInterfaceInterceptors() |
|||
.InterceptedBy(typeof(RecordingInterceptor))); |
|||
|
|||
typeof(INullableCalculator).CustomAttributes.ShouldContain(a => a.AttributeType.Name == "NullableContextAttribute"); |
|||
container.Resolve<INullableCalculator>().GetType().FullName.ShouldStartWith("Castle.Proxies.INullableCalculatorProxy"); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Interface_Interception_Should_Keep_A_Runtime_Attribute_Of_The_Compiler_Namespace_On_The_Proxy() |
|||
{ |
|||
using var container = Build(builder => builder.RegisterType<ForwardedCalculator>() |
|||
.As<IForwardedCalculator>() |
|||
.EnableAbpInterfaceInterceptors() |
|||
.InterceptedBy(typeof(RecordingInterceptor))); |
|||
|
|||
typeof(ForwardedCalculator).GetInterfaces().First().ShouldBe(typeof(IForwardedExtra)); |
|||
var proxyType = container.Resolve<IForwardedCalculator>().GetType(); |
|||
proxyType.FullName.ShouldStartWith("Castle.Proxies.IForwardedExtraProxy"); |
|||
proxyType.GetCustomAttributes(typeof(System.Runtime.CompilerServices.TypeForwardedFromAttribute), false).ShouldNotBeEmpty(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Interface_Proxies_Of_A_Shared_Interface_Should_Keep_Distinct_Names_For_Caches_Keyed_By_Name() |
|||
{ |
|||
var targets = PropertyTargets(); |
|||
using var container = Build(builder => |
|||
{ |
|||
for (var i = 0; i < targets.Length; i++) |
|||
{ |
|||
builder.RegisterType(targets[i]).Keyed<IPropertyTarget>(i).EnableAbpInterfaceInterceptors().InterceptedBy(typeof(RecordingInterceptor)); |
|||
} |
|||
}); |
|||
|
|||
var proxies = Enumerable.Range(0, targets.Length).Select(i => container.ResolveKeyed<IPropertyTarget>(i)).ToArray(); |
|||
|
|||
proxies.Select(proxy => proxy.GetType().FullName).Distinct().Count().ShouldBe(targets.Length); |
|||
for (var i = 0; i < proxies.Length; i++) |
|||
{ |
|||
var value = i; |
|||
ObjectHelper.TrySetProperty(proxies[i], x => x.Value, () => value); |
|||
((IPropertyTarget)ProxyUtil.GetUnproxiedInstance(proxies[i])).Value.ShouldBe(i); |
|||
} |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Every_Proxy_Kind_Should_Intercept_Through_The_Sharded_Builder() |
|||
{ |
|||
var generator = new ProxyGenerator(new AbpShardedProxyBuilder(4)); |
|||
var interceptor = new RecordingInterceptor("counted"); |
|||
|
|||
generator.CreateClassProxy<Calculator>(interceptor).Add(1, 2).ShouldBe(3); |
|||
generator.CreateClassProxyWithTarget(new Calculator(), interceptor).Add(1, 2).ShouldBe(3); |
|||
generator.CreateInterfaceProxyWithTarget<ICalculator>(new Calculator(), interceptor).Add(1, 2).ShouldBe(3); |
|||
generator.CreateInterfaceProxyWithTargetInterface<ICalculator>(new Calculator(), interceptor).Add(1, 2).ShouldBe(3); |
|||
generator.CreateInterfaceProxyWithoutTarget<ICalculator>(new ReturningInterceptor(7)).Add(1, 2).ShouldBe(7); |
|||
(await generator.CreateClassProxy<Calculator>(interceptor).AddAsync(2, 3)).ShouldBe(5); |
|||
Should.Throw<InvalidOperationException>(() => generator.CreateClassProxy<Calculator>(interceptor).Fail()); |
|||
|
|||
interceptor.Calls.Count.ShouldBe(6); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Class_Interception_Should_Pass_The_Options_Selector_To_The_Proxy() |
|||
{ |
|||
var options = new ProxyGenerationOptions { Selector = new NoInterceptorsSelector() }; |
|||
using var container = Build(builder => builder.RegisterType<Calculator>() |
|||
.EnableAbpClassInterceptors(options) |
|||
.InterceptedBy(typeof(RecordingInterceptor))); |
|||
|
|||
container.Resolve<Calculator>().Add(1, 2).ShouldBe(3); |
|||
|
|||
container.Resolve<RecordingInterceptor>().Calls.ShouldBeEmpty(); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Class_Interception_Should_Pass_The_Options_Mixins_To_The_Proxy() |
|||
{ |
|||
var options = new ProxyGenerationOptions(); |
|||
options.AddMixinInstance(new Extra()); |
|||
using var container = Build(builder => builder.RegisterType<Calculator>() |
|||
.EnableAbpClassInterceptors(options) |
|||
.InterceptedBy(typeof(RecordingInterceptor))); |
|||
|
|||
var calculator = container.Resolve<Calculator>(); |
|||
|
|||
calculator.Add(1, 2).ShouldBe(3); |
|||
((IExtra)calculator).Seven().ShouldBe(7); |
|||
container.Resolve<RecordingInterceptor>().Calls.ShouldBe(new[] { "counted:Add", "counted:Seven" }); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Class_Interception_Should_Run_Explicit_Then_Attribute_Interceptors() |
|||
{ |
|||
using var container = Build(builder => builder.RegisterType<AttributedCalculator>() |
|||
.EnableAbpClassInterceptors() |
|||
.InterceptedBy(typeof(RecordingInterceptor))); |
|||
|
|||
container.Resolve<AttributedCalculator>().Add(1, 2).ShouldBe(3); |
|||
|
|||
CallsOf(container).ShouldBe(new[] { "counted:Add", "attribute:Add" }); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Interface_Interception_Should_Run_Explicit_Named_And_Attribute_Interceptors() |
|||
{ |
|||
using var container = Build(builder => builder.RegisterType<AttributedCalculator>() |
|||
.As<ICalculator>() |
|||
.EnableAbpInterfaceInterceptors() |
|||
.InterceptedBy(typeof(RecordingInterceptor)) |
|||
.InterceptedBy("named")); |
|||
|
|||
container.Resolve<ICalculator>().Add(1, 2).ShouldBe(3); |
|||
|
|||
CallsOf(container).ShouldBe(new[] { "counted:Add", "named:Add", "attribute:Add" }); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Interface_Interception_Should_Pass_The_Options_To_The_Proxy() |
|||
{ |
|||
var options = new ProxyGenerationOptions { Selector = new NoInterceptorsSelector() }; |
|||
using var container = Build(builder => builder.RegisterType<Calculator>() |
|||
.As<ICalculator>() |
|||
.EnableAbpInterfaceInterceptors(options) |
|||
.InterceptedBy(typeof(RecordingInterceptor))); |
|||
|
|||
container.Resolve<ICalculator>().Add(1, 2).ShouldBe(3); |
|||
|
|||
container.Resolve<RecordingInterceptor>().Calls.ShouldBeEmpty(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task The_Shard_Count_Should_Be_Fixed_Once_The_Generator_Exists() |
|||
{ |
|||
var generators = await Task.WhenAll(Enumerable.Range(0, 8) |
|||
.Select(_ => Task.Run(() => AbpInterceptionRegistrationExtensions.ProxyGenerator))); |
|||
var generator = generators.Distinct().ShouldHaveSingleItem(); |
|||
var shardCount = AbpInterceptionRegistrationExtensions.ShardCount; |
|||
|
|||
generator.ProxyBuilder.ShouldBeOfType<AbpShardedProxyBuilder>().ShardCount.ShouldBe(shardCount); |
|||
AbpInterceptionRegistrationExtensions.ShardCount = shardCount; |
|||
Should.Throw<AbpException>(() => AbpInterceptionRegistrationExtensions.ShardCount = shardCount + 1); |
|||
Should.Throw<ArgumentException>(() => AbpInterceptionRegistrationExtensions.ShardCount = 0); |
|||
AbpInterceptionRegistrationExtensions.ShardCount.ShouldBe(shardCount); |
|||
} |
|||
|
|||
private static IContainer Build(Action<ContainerBuilder> register) |
|||
{ |
|||
var builder = new ContainerBuilder(); |
|||
builder.RegisterType<RecordingInterceptor>().AsSelf().SingleInstance() |
|||
.WithParameter(new TypedParameter(typeof(string), "counted")); |
|||
builder.Register(_ => new RecordingInterceptor("named")).Named<IInterceptor>("named").SingleInstance(); |
|||
builder.Register(_ => new AttributeInterceptor()).AsSelf().SingleInstance(); |
|||
register(builder); |
|||
return builder.Build(); |
|||
} |
|||
|
|||
private static List<string> CallsOf(IContainer container) |
|||
{ |
|||
return container.Resolve<RecordingInterceptor>().Recorded |
|||
.Concat(((RecordingInterceptor)container.ResolveNamed<IInterceptor>("named")).Recorded) |
|||
.Concat(container.Resolve<AttributeInterceptor>().Recorded) |
|||
.OrderBy(call => call.Order) |
|||
.Select(call => call.Name) |
|||
.ToList(); |
|||
} |
|||
|
|||
private static Type[] DistinctlyNamedTypes() |
|||
{ |
|||
return new[] |
|||
{ |
|||
typeof(Spread01), typeof(Spread02), typeof(Spread03), typeof(Spread04), typeof(Spread05), typeof(Spread06), |
|||
typeof(Spread07), typeof(Spread08), typeof(Spread09), typeof(Spread10), typeof(Spread11), typeof(Spread12) |
|||
}; |
|||
} |
|||
|
|||
private static Type[] CalculatorTargets() |
|||
{ |
|||
return new[] |
|||
{ |
|||
typeof(Calculator), typeof(Calculator<int>), typeof(Calculator<string>), typeof(Calculator<long>), |
|||
typeof(Calculator<byte>), typeof(Calculator<short>), typeof(Calculator<char>), typeof(Calculator<bool>), |
|||
typeof(Calculator<double>), typeof(Calculator<float>), typeof(Calculator<decimal>), typeof(Calculator<Guid>) |
|||
}; |
|||
} |
|||
|
|||
private static Type[] PropertyTargets() |
|||
{ |
|||
return new[] |
|||
{ |
|||
typeof(PropertyTarget01), typeof(PropertyTarget02), typeof(PropertyTarget03), typeof(PropertyTarget04), |
|||
typeof(PropertyTarget05), typeof(PropertyTarget06), typeof(PropertyTarget07), typeof(PropertyTarget08), |
|||
typeof(PropertyTarget09), typeof(PropertyTarget10), typeof(PropertyTarget11), typeof(PropertyTarget12) |
|||
}; |
|||
} |
|||
|
|||
private static Type[] SameNamedTypes() |
|||
{ |
|||
return new[] |
|||
{ |
|||
typeof(int), typeof(long), typeof(short), typeof(byte), typeof(string), typeof(Guid), typeof(DateTime), |
|||
typeof(decimal), typeof(double), typeof(float), typeof(char), typeof(bool), typeof(object), typeof(Uri), |
|||
typeof(Version), typeof(TimeSpan) |
|||
} |
|||
.Select(argument => typeof(Target<>).MakeGenericType(argument)) |
|||
.ToArray(); |
|||
} |
|||
|
|||
public interface ICalculator |
|||
{ |
|||
int Add(int a, int b); |
|||
} |
|||
|
|||
public class Calculator<T> : ICalculator |
|||
{ |
|||
public virtual int Add(int a, int b) => a + b; |
|||
} |
|||
|
|||
#nullable enable |
|||
public interface INullableCalculator |
|||
{ |
|||
string? Describe(string? value); |
|||
|
|||
string Name(); |
|||
} |
|||
|
|||
public class NullableCalculator : IExtra, INullableCalculator |
|||
{ |
|||
public int Seven() => 7; |
|||
|
|||
public string? Describe(string? value) => value; |
|||
|
|||
public string Name() => "name"; |
|||
} |
|||
#nullable restore |
|||
|
|||
public interface IOwnInterfaceCalculator |
|||
{ |
|||
int Add(int a, int b); |
|||
} |
|||
|
|||
public class OwnInterfaceCalculator : IExtra, IOwnInterfaceCalculator |
|||
{ |
|||
public int Add(int a, int b) => a + b; |
|||
|
|||
public int Seven() => 7; |
|||
} |
|||
|
|||
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, Inherited = false)] |
|||
public class ProxyTagAttribute : Attribute |
|||
{ |
|||
public string Tag { get; } |
|||
|
|||
public ProxyTagAttribute(string tag) |
|||
{ |
|||
Tag = tag; |
|||
} |
|||
} |
|||
|
|||
[ProxyTag("extra")] |
|||
public interface ITaggedExtra |
|||
{ |
|||
int Eight(); |
|||
} |
|||
|
|||
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class)] |
|||
public class InheritedProxyTagAttribute : Attribute |
|||
{ |
|||
public string Tag { get; } |
|||
|
|||
public InheritedProxyTagAttribute(string tag) |
|||
{ |
|||
Tag = tag; |
|||
} |
|||
} |
|||
|
|||
[InheritedProxyTag("replicated")] |
|||
public interface IReplicatedExtra |
|||
{ |
|||
int Nine(); |
|||
} |
|||
|
|||
public interface IReplicatedCalculator |
|||
{ |
|||
int Add(int a, int b); |
|||
} |
|||
|
|||
public class ReplicatedCalculator : IReplicatedExtra, IReplicatedCalculator |
|||
{ |
|||
public int Add(int a, int b) => a + b; |
|||
|
|||
public int Nine() => 9; |
|||
} |
|||
|
|||
[System.Runtime.CompilerServices.TypeForwardedFrom("Original, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")] |
|||
public interface IForwardedExtra |
|||
{ |
|||
int Ten(); |
|||
} |
|||
|
|||
public interface IForwardedCalculator |
|||
{ |
|||
int Add(int a, int b); |
|||
} |
|||
|
|||
public class ForwardedCalculator : IForwardedExtra, IForwardedCalculator |
|||
{ |
|||
public int Add(int a, int b) => a + b; |
|||
|
|||
public int Ten() => 10; |
|||
} |
|||
|
|||
public interface ITaggedCalculator |
|||
{ |
|||
int Add(int a, int b); |
|||
} |
|||
|
|||
public class TaggedCalculator : ITaggedExtra, ITaggedCalculator |
|||
{ |
|||
public int Add(int a, int b) => a + b; |
|||
|
|||
public int Eight() => 8; |
|||
} |
|||
|
|||
public interface IPropertyTarget |
|||
{ |
|||
int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget01 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget02 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget03 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget04 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget05 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget06 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget07 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget08 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget09 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget10 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget11 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class PropertyTarget12 : IPropertyTarget |
|||
{ |
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public interface IExtra |
|||
{ |
|||
int Seven(); |
|||
} |
|||
|
|||
public class Calculator : ICalculator |
|||
{ |
|||
public virtual int Add(int a, int b) => a + b; |
|||
|
|||
public virtual Task<int> AddAsync(int a, int b) => Task.FromResult(a + b); |
|||
|
|||
public virtual int Fail() => throw new InvalidOperationException("Failed."); |
|||
} |
|||
|
|||
[Intercept(typeof(AttributeInterceptor))] |
|||
public class AttributedCalculator : Calculator |
|||
{ |
|||
} |
|||
|
|||
public class Extra : IExtra |
|||
{ |
|||
public int Seven() => 7; |
|||
} |
|||
|
|||
public class Spread01 |
|||
{ |
|||
public virtual int Value() => 1; |
|||
} |
|||
|
|||
public class Spread02 |
|||
{ |
|||
public virtual int Value() => 2; |
|||
} |
|||
|
|||
public class Spread03 |
|||
{ |
|||
public virtual int Value() => 3; |
|||
} |
|||
|
|||
public class Spread04 |
|||
{ |
|||
public virtual int Value() => 4; |
|||
} |
|||
|
|||
public class Spread05 |
|||
{ |
|||
public virtual int Value() => 5; |
|||
} |
|||
|
|||
public class Spread06 |
|||
{ |
|||
public virtual int Value() => 6; |
|||
} |
|||
|
|||
public class Spread07 |
|||
{ |
|||
public virtual int Value() => 7; |
|||
} |
|||
|
|||
public class Spread08 |
|||
{ |
|||
public virtual int Value() => 8; |
|||
} |
|||
|
|||
public class Spread09 |
|||
{ |
|||
public virtual int Value() => 9; |
|||
} |
|||
|
|||
public class Spread10 |
|||
{ |
|||
public virtual int Value() => 10; |
|||
} |
|||
|
|||
public class Spread11 |
|||
{ |
|||
public virtual int Value() => 11; |
|||
} |
|||
|
|||
public class Spread12 |
|||
{ |
|||
public virtual int Value() => 12; |
|||
} |
|||
|
|||
public class FirstOwner |
|||
{ |
|||
public class Handler |
|||
{ |
|||
public virtual int Value() => 1; |
|||
} |
|||
} |
|||
|
|||
public class SecondOwner |
|||
{ |
|||
public class Handler |
|||
{ |
|||
public virtual int Value() => 2; |
|||
} |
|||
} |
|||
|
|||
public class Target<T> |
|||
{ |
|||
public virtual T? Echo(T? value) => value; |
|||
} |
|||
|
|||
public class RecordingInterceptor : IInterceptor |
|||
{ |
|||
private static int _order; |
|||
|
|||
private readonly string _name; |
|||
|
|||
public RecordingInterceptor(string name) |
|||
{ |
|||
_name = name; |
|||
} |
|||
|
|||
public List<string> Calls => Recorded.Select(call => call.Name).ToList(); |
|||
|
|||
public List<(int Order, string Name)> Recorded { get; } = new(); |
|||
|
|||
public void Intercept(IInvocation invocation) |
|||
{ |
|||
lock (Recorded) |
|||
{ |
|||
Recorded.Add((System.Threading.Interlocked.Increment(ref _order), $"{_name}:{invocation.Method.Name}")); |
|||
} |
|||
|
|||
invocation.Proceed(); |
|||
} |
|||
} |
|||
|
|||
public class AttributeInterceptor : RecordingInterceptor |
|||
{ |
|||
public AttributeInterceptor() |
|||
: base("attribute") |
|||
{ |
|||
} |
|||
} |
|||
|
|||
public class ReturningInterceptor : IInterceptor |
|||
{ |
|||
private readonly int _value; |
|||
|
|||
public ReturningInterceptor(int value) |
|||
{ |
|||
_value = value; |
|||
} |
|||
|
|||
public void Intercept(IInvocation invocation) |
|||
{ |
|||
invocation.ReturnValue = _value; |
|||
} |
|||
} |
|||
|
|||
public class NoInterceptorsSelector : IInterceptorSelector |
|||
{ |
|||
public IInterceptor[] SelectInterceptors(Type type, System.Reflection.MethodInfo method, IInterceptor[] interceptors) |
|||
{ |
|||
return Array.Empty<IInterceptor>(); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,86 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Autofac.Builder; |
|||
using Castle.DynamicProxy; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.DynamicProxy; |
|||
using Volo.Abp.TestBase.Logging; |
|||
using Volo.Abp.Testing; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Autofac.Interception; |
|||
|
|||
public class Autofac_Interface_Interception_Test : AbpAsyncIntegratedTest<AutofacTestModule>, IAsyncLifetime |
|||
{ |
|||
protected override Task<Action<AbpApplicationCreationOptions>> SetAbpApplicationCreationOptionsAsync() |
|||
{ |
|||
return Task.FromResult<Action<AbpApplicationCreationOptions>>(options => options.UseAutofac()); |
|||
} |
|||
|
|||
protected override Task BeforeAddApplicationAsync(IServiceCollection services) |
|||
{ |
|||
services.AddTransient<SimpleAsyncInterceptor>(); |
|||
services.AddTransient<IInterfaceInterceptionTarget, InterfaceInterceptionTarget>(); |
|||
services.OnRegistered(registration => |
|||
{ |
|||
if (typeof(InterfaceInterceptionTarget) == registration.ImplementationType) |
|||
{ |
|||
registration.Interceptors.Add<SimpleAsyncInterceptor>(); |
|||
} |
|||
}); |
|||
|
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Intercept_A_Service_Registered_By_Its_Interface() |
|||
{ |
|||
var target = GetRequiredService<IInterfaceInterceptionTarget>(); |
|||
|
|||
ProxyUtil.IsProxy(target).ShouldBeTrue(); |
|||
(await target.GetValueAsync()).ShouldBe(42); |
|||
// Read from the target itself: reading Logs through the proxy is intercepted too.
|
|||
((InterfaceInterceptionTarget)ProxyUtil.GetUnproxiedInstance(target)).Logs.ShouldBe(new[] |
|||
{ |
|||
"SimpleAsyncInterceptor_InterceptAsync_BeforeInvocation", |
|||
"ExecutingGetValueAsync", |
|||
"SimpleAsyncInterceptor_InterceptAsync_AfterInvocation" |
|||
}); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Generate_The_Proxy_With_The_Sharded_Generator() |
|||
{ |
|||
var target = GetRequiredService<IInterfaceInterceptionTarget>(); |
|||
|
|||
var targetType = typeof(InterfaceInterceptionTarget); |
|||
var additionalInterfaces = targetType.GetInterfaces() |
|||
.Where(ProxyUtil.IsAccessible) |
|||
.Where(i => i != typeof(IInterfaceInterceptionTarget)) |
|||
.ToArray(); |
|||
var proxyType = AbpInterceptionRegistrationExtensions.ProxyGenerator.ProxyBuilder.CreateInterfaceProxyTypeWithTarget( |
|||
typeof(IInterfaceInterceptionTarget), additionalInterfaces, targetType, ProxyGenerationOptions.Default); |
|||
|
|||
// The same key returns the cached type only from the generator that built the resolved proxy.
|
|||
target.GetType().ShouldBeSameAs(proxyType); |
|||
} |
|||
|
|||
public interface IInterfaceInterceptionTarget : ICanLogOnObject |
|||
{ |
|||
Task<int> GetValueAsync(); |
|||
} |
|||
|
|||
public class InterfaceInterceptionTarget : IInterfaceInterceptionTarget |
|||
{ |
|||
public List<string> Logs { get; } = new(); |
|||
|
|||
public Task<int> GetValueAsync() |
|||
{ |
|||
Logs.Add("ExecutingGetValueAsync"); |
|||
return Task.FromResult(42); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,72 @@ |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Autofac; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.EventBus.Distributed; |
|||
|
|||
public class LocalDistributedEventBus_RegisteredHandlerType_Tests : LocalDistributedEventBusTestBase |
|||
{ |
|||
protected override void AfterAddApplication(IServiceCollection services) |
|||
{ |
|||
// Registered with Autofac directly, so the handler is not also subscribed to the application's bus by convention.
|
|||
var builder = services.GetObject<ContainerBuilder>(); |
|||
builder.RegisterType<CreationCounter>().SingleInstance(); |
|||
builder.RegisterType<CountedDistributedEventHandler>(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Distributed_Ioc_Handler_Should_Be_Created_Once_Per_Publish() |
|||
{ |
|||
var counter = GetRequiredService<CreationCounter>(); |
|||
var factory = new IocEventHandlerFactory(GetRequiredService<IServiceScopeFactory>(), typeof(CountedDistributedEventHandler)); |
|||
|
|||
using (DistributedEventBus.Subscribe(typeof(CountedDistributedEventData), factory)) |
|||
{ |
|||
for (var i = 0; i < 3; i++) |
|||
{ |
|||
await DistributedEventBus.PublishAsync(new CountedDistributedEventData(), onUnitOfWorkComplete: false); |
|||
} |
|||
} |
|||
|
|||
counter.Handled.ShouldBe(3); |
|||
counter.Created.ShouldBe(3); |
|||
} |
|||
|
|||
public class CountedDistributedEventData |
|||
{ |
|||
} |
|||
|
|||
public class CreationCounter |
|||
{ |
|||
private int _created; |
|||
private int _handled; |
|||
|
|||
public int Created => _created; |
|||
|
|||
public int Handled => _handled; |
|||
|
|||
public void OnCreated() => Interlocked.Increment(ref _created); |
|||
|
|||
public void OnHandled() => Interlocked.Increment(ref _handled); |
|||
} |
|||
|
|||
public class CountedDistributedEventHandler : IDistributedEventHandler<CountedDistributedEventData> |
|||
{ |
|||
private readonly CreationCounter _counter; |
|||
|
|||
public CountedDistributedEventHandler(CreationCounter counter) |
|||
{ |
|||
_counter = counter; |
|||
_counter.OnCreated(); |
|||
} |
|||
|
|||
public Task HandleEventAsync(CountedDistributedEventData eventData) |
|||
{ |
|||
_counter.OnHandled(); |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
} |
|||
@ -1,8 +1,9 @@ |
|||
using Volo.Abp.Autofac; |
|||
using Volo.Abp.Modularity; |
|||
|
|||
namespace Volo.Abp.EventBus; |
|||
|
|||
[DependsOn(typeof(AbpEventBusModule))] |
|||
[DependsOn(typeof(AbpEventBusModule), typeof(AbpAutofacModule))] |
|||
public class EventBusTestModule : AbpModule |
|||
{ |
|||
} |
|||
|
|||
@ -0,0 +1,241 @@ |
|||
using System; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.EventBus.Local; |
|||
|
|||
public class IocEventHandlerFactory_Tests : EventBusTestBase |
|||
{ |
|||
protected override void AfterAddApplication(IServiceCollection services) |
|||
{ |
|||
AddThrowingHandler(services); |
|||
} |
|||
|
|||
[Fact] |
|||
public void A_Handler_That_Fails_To_Construct_Should_Not_Leave_Its_Scope_Undisposed_With_Autofac() |
|||
{ |
|||
var tracker = GetRequiredService<ScopeTracker>(); |
|||
var factory = new IocEventHandlerFactory(GetRequiredService<IServiceScopeFactory>(), typeof(ThrowingHandler)); |
|||
|
|||
Should.Throw<Exception>(() => factory.GetHandler()); |
|||
|
|||
tracker.Created.ShouldBe(1); |
|||
tracker.Disposed.ShouldBe(1); |
|||
} |
|||
|
|||
[Fact] |
|||
public void A_Handler_That_Fails_To_Construct_Should_Not_Leave_Its_Scope_Undisposed_With_Microsoft_DI() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
AddThrowingHandler(services); |
|||
using var provider = services.BuildServiceProvider(); |
|||
var tracker = provider.GetRequiredService<ScopeTracker>(); |
|||
var factory = new IocEventHandlerFactory(provider.GetRequiredService<IServiceScopeFactory>(), typeof(ThrowingHandler)); |
|||
|
|||
Should.Throw<InvalidOperationException>(() => factory.GetHandler()).Message.ShouldBe("Handler construction failed."); |
|||
|
|||
tracker.Created.ShouldBe(1); |
|||
tracker.Disposed.ShouldBe(1); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Publishing_To_A_Handler_That_Fails_To_Construct_Should_Dispose_Every_Scope_It_Opened() |
|||
{ |
|||
var tracker = GetRequiredService<ScopeTracker>(); |
|||
using (LocalEventBus.Subscribe(typeof(ThrowingHandlerEventData), new IocEventHandlerFactory(GetRequiredService<IServiceScopeFactory>(), typeof(ThrowingHandler)))) |
|||
{ |
|||
await Should.ThrowAsync<Exception>(() => LocalEventBus.PublishAsync(new ThrowingHandlerEventData())); |
|||
} |
|||
|
|||
tracker.Created.ShouldBeGreaterThan(0); |
|||
tracker.Disposed.ShouldBe(tracker.Created); |
|||
} |
|||
|
|||
[Fact] |
|||
public void A_Handler_That_Fails_To_Construct_Should_Report_Its_Own_Exception_When_Its_Scope_Fails_To_Dispose() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
services.AddScoped<DisposeFailingDependency>(); |
|||
services.AddTransient<HandlerWithDisposeFailingDependency>(); |
|||
using var provider = services.BuildServiceProvider(); |
|||
var factory = new IocEventHandlerFactory(provider.GetRequiredService<IServiceScopeFactory>(), typeof(HandlerWithDisposeFailingDependency)); |
|||
|
|||
Should.Throw<InvalidOperationException>(() => factory.GetHandler()).Message.ShouldBe("Handler construction failed."); |
|||
} |
|||
|
|||
[Fact] |
|||
public void A_Resolved_Handler_Should_Keep_Its_Scope_Until_It_Is_Disposed() |
|||
{ |
|||
var tracker = GetRequiredService<ScopeTracker>(); |
|||
var factory = new IocEventHandlerFactory(GetRequiredService<IServiceScopeFactory>(), typeof(WorkingHandler)); |
|||
|
|||
var wrapper = factory.GetHandler(); |
|||
wrapper.EventHandler.ShouldBeOfType<WorkingHandler>().Dependency.IsDisposed.ShouldBeFalse(); |
|||
tracker.Created.ShouldBe(1); |
|||
tracker.Disposed.ShouldBe(0); |
|||
|
|||
wrapper.Dispose(); |
|||
tracker.Disposed.ShouldBe(1); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Handler_That_Fails_To_Construct_While_Ordering_Should_Dispose_Both_Without_Invoking_Either() |
|||
{ |
|||
// A Microsoft container of its own: it does not tell the handler types, so both are created to read their
|
|||
// order, and neither is also subscribed to the application's bus by convention.
|
|||
var services = new ServiceCollection(); |
|||
AddThrowingHandler(services); |
|||
services.AddTransient<EarlierWorkingHandler>(); |
|||
services.AddTransient<LaterThrowingHandler>(); |
|||
await using var provider = services.BuildServiceProvider(); |
|||
var tracker = provider.GetRequiredService<ScopeTracker>(); |
|||
var scopeFactory = provider.GetRequiredService<IServiceScopeFactory>(); |
|||
using (LocalEventBus.Subscribe(typeof(OrderingFailureEventData), new IocEventHandlerFactory(scopeFactory, typeof(EarlierWorkingHandler)))) |
|||
using (LocalEventBus.Subscribe(typeof(OrderingFailureEventData), new IocEventHandlerFactory(scopeFactory, typeof(LaterThrowingHandler)))) |
|||
{ |
|||
await Should.ThrowAsync<Exception>(() => LocalEventBus.PublishAsync(new OrderingFailureEventData())); |
|||
} |
|||
|
|||
tracker.Handled.ShouldBe(0); |
|||
tracker.Created.ShouldBe(2); |
|||
tracker.Disposed.ShouldBe(2); |
|||
} |
|||
|
|||
private static void AddThrowingHandler(IServiceCollection services) |
|||
{ |
|||
services.AddSingleton<ScopeTracker>(); |
|||
services.AddScoped<ScopedDependency>(); |
|||
services.AddTransient<ThrowingHandler>(); |
|||
services.AddTransient<WorkingHandler>(); |
|||
} |
|||
|
|||
public class ThrowingHandlerEventData |
|||
{ |
|||
} |
|||
|
|||
public class OrderingFailureEventData |
|||
{ |
|||
} |
|||
|
|||
public class DisposeFailingDependency : IDisposable |
|||
{ |
|||
public void Dispose() |
|||
{ |
|||
throw new ApplicationException("Scope disposal failed."); |
|||
} |
|||
} |
|||
|
|||
public class HandlerWithDisposeFailingDependency : ILocalEventHandler<OrderingFailureEventData> |
|||
{ |
|||
public HandlerWithDisposeFailingDependency(DisposeFailingDependency dependency) |
|||
{ |
|||
throw new InvalidOperationException("Handler construction failed."); |
|||
} |
|||
|
|||
public Task HandleEventAsync(OrderingFailureEventData eventData) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
public class ScopeTracker |
|||
{ |
|||
private int _created; |
|||
private int _disposed; |
|||
private int _handled; |
|||
|
|||
public int Created => _created; |
|||
|
|||
public int Disposed => _disposed; |
|||
|
|||
public int Handled => _handled; |
|||
|
|||
public void OnHandled() => Interlocked.Increment(ref _handled); |
|||
|
|||
public void OnCreated() => Interlocked.Increment(ref _created); |
|||
|
|||
public void OnDisposed() => Interlocked.Increment(ref _disposed); |
|||
} |
|||
|
|||
public class ScopedDependency : IDisposable |
|||
{ |
|||
private readonly ScopeTracker _tracker; |
|||
|
|||
public ScopeTracker Tracker => _tracker; |
|||
|
|||
public bool IsDisposed { get; private set; } |
|||
|
|||
public ScopedDependency(ScopeTracker tracker) |
|||
{ |
|||
_tracker = tracker; |
|||
_tracker.OnCreated(); |
|||
} |
|||
|
|||
public void Dispose() |
|||
{ |
|||
IsDisposed = true; |
|||
_tracker.OnDisposed(); |
|||
} |
|||
} |
|||
|
|||
public class ThrowingHandler : ILocalEventHandler<ThrowingHandlerEventData> |
|||
{ |
|||
public ThrowingHandler(ScopedDependency dependency) |
|||
{ |
|||
throw new InvalidOperationException("Handler construction failed."); |
|||
} |
|||
|
|||
public Task HandleEventAsync(ThrowingHandlerEventData eventData) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
public class WorkingHandler : ILocalEventHandler<ThrowingHandlerEventData> |
|||
{ |
|||
public ScopedDependency Dependency { get; } |
|||
|
|||
public WorkingHandler(ScopedDependency dependency) |
|||
{ |
|||
Dependency = dependency; |
|||
} |
|||
|
|||
public Task HandleEventAsync(ThrowingHandlerEventData eventData) |
|||
{ |
|||
Dependency.Tracker.OnHandled(); |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
public class EarlierWorkingHandler : ILocalEventHandler<OrderingFailureEventData> |
|||
{ |
|||
private readonly ScopedDependency _dependency; |
|||
|
|||
public EarlierWorkingHandler(ScopedDependency dependency) |
|||
{ |
|||
_dependency = dependency; |
|||
} |
|||
|
|||
public Task HandleEventAsync(OrderingFailureEventData eventData) |
|||
{ |
|||
_dependency.Tracker.OnHandled(); |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
public class LaterThrowingHandler : ILocalEventHandler<OrderingFailureEventData> |
|||
{ |
|||
public LaterThrowingHandler(ScopedDependency dependency) |
|||
{ |
|||
throw new InvalidOperationException("Handler construction failed."); |
|||
} |
|||
|
|||
public Task HandleEventAsync(OrderingFailureEventData eventData) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,218 @@ |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Options; |
|||
using Shouldly; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Volo.Abp.Uow; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.EventBus.Local; |
|||
|
|||
public class LocalEventBus_HandlerConstruction_Tests : EventBusTestBase |
|||
{ |
|||
[Fact] |
|||
public async Task A_Later_Handler_Should_Be_Created_After_An_Earlier_One_Ran() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
services.AddSingleton<ConstructionState>(); |
|||
services.AddTransient<StateWritingHandler>(); |
|||
services.AddTransient<StateReadingHandler>(); |
|||
await using var provider = services.BuildServiceProvider(); |
|||
var scopeFactory = provider.GetRequiredService<IServiceScopeFactory>(); |
|||
|
|||
using (LocalEventBus.Subscribe(typeof(StateEventData), new IocEventHandlerFactory(scopeFactory, typeof(StateReadingHandler)))) |
|||
using (LocalEventBus.Subscribe(typeof(StateEventData), new IocEventHandlerFactory(scopeFactory, typeof(StateWritingHandler)))) |
|||
{ |
|||
await LocalEventBus.PublishAsync(new StateEventData()); |
|||
} |
|||
|
|||
provider.GetRequiredService<ConstructionState>().SeenByReader.ShouldBe(42); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Handler_Created_To_Read_Its_Order_Should_Not_Stop_The_Publish_When_It_Fails_To_Dispose() |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
services.AddSingleton<ConstructionState>(); |
|||
services.AddTransient<DisposeFailingStateHandler>(); |
|||
await using var provider = services.BuildServiceProvider(); |
|||
|
|||
using (LocalEventBus.Subscribe(typeof(StateEventData), new IocEventHandlerFactory(provider.GetRequiredService<IServiceScopeFactory>(), typeof(DisposeFailingStateHandler)))) |
|||
{ |
|||
// The instance that handled the event still fails to dispose afterwards, as it did before.
|
|||
await Should.ThrowAsync<System.InvalidOperationException>(() => LocalEventBus.PublishAsync(new StateEventData())); |
|||
} |
|||
|
|||
provider.GetRequiredService<ConstructionState>().Value.ShouldBe(1); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Handler_That_Fails_To_Resolve_While_Its_Order_Is_Read_Should_Still_Be_Disposed() |
|||
{ |
|||
var factory = new LazilyFailingHandlerFactory(); |
|||
var eventName = "Volo.Abp.EventBus.Local.LocalEventBus_HandlerConstruction_Tests.LazilyFailing"; |
|||
using (LocalEventBus.Subscribe(eventName, factory)) |
|||
{ |
|||
(await Should.ThrowAsync<System.InvalidOperationException>(() => LocalEventBus.PublishAsync(eventName, new { }, onUnitOfWorkComplete: false))) |
|||
.Message.ShouldBe("Lazy resolution failed."); |
|||
} |
|||
|
|||
factory.Disposed.ShouldBe(1); |
|||
} |
|||
|
|||
public class LazilyFailingHandlerFactory : IEventHandlerFactory |
|||
{ |
|||
public int Disposed { get; private set; } |
|||
|
|||
public IEventHandlerDisposeWrapper GetHandler() |
|||
{ |
|||
return new LazilyFailingHandlerWrapper(this); |
|||
} |
|||
|
|||
public bool IsInFactories(List<IEventHandlerFactory> handlerFactories) |
|||
{ |
|||
return handlerFactories.Contains(this); |
|||
} |
|||
|
|||
private class LazilyFailingHandlerWrapper : IEventHandlerDisposeWrapper |
|||
{ |
|||
private readonly LazilyFailingHandlerFactory _factory; |
|||
|
|||
public LazilyFailingHandlerWrapper(LazilyFailingHandlerFactory factory) |
|||
{ |
|||
_factory = factory; |
|||
} |
|||
|
|||
public IEventHandler EventHandler => throw new System.InvalidOperationException("Lazy resolution failed."); |
|||
|
|||
public void Dispose() |
|||
{ |
|||
_factory.Disposed++; |
|||
} |
|||
} |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Derived_Bus_Should_Choose_The_Handlers_Of_A_Mapped_Dynamic_Event() |
|||
{ |
|||
var bus = ActivatorUtilities.CreateInstance<FilteringLocalEventBus>(ServiceProvider); |
|||
var handled = 0; |
|||
using (bus.Subscribe<FilteredEventData>(_ => |
|||
{ |
|||
handled++; |
|||
return Task.CompletedTask; |
|||
})) |
|||
{ |
|||
await bus.TriggerHandlersAsync(typeof(DynamicEventData), new DynamicEventData(FilteredEventData.Name, new { })); |
|||
await bus.PublishAsync(new FilteredEventData(), onUnitOfWorkComplete: false); |
|||
} |
|||
|
|||
handled.ShouldBe(0); |
|||
bus.FilteredCalls.ShouldBe(2); |
|||
} |
|||
|
|||
[EventName(Name)] |
|||
public class FilteredEventData |
|||
{ |
|||
public const string Name = "Volo.Abp.EventBus.Local.LocalEventBus_HandlerConstruction_Tests.Filtered"; |
|||
} |
|||
|
|||
// Kept out of conventional registration, which would make it the application's bus.
|
|||
[DisableConventionalRegistration] |
|||
public class FilteringLocalEventBus : LocalEventBus |
|||
{ |
|||
public int FilteredCalls { get; private set; } |
|||
|
|||
public FilteringLocalEventBus( |
|||
IOptions<AbpLocalEventBusOptions> options, |
|||
IServiceScopeFactory serviceScopeFactory, |
|||
ICurrentTenant currentTenant, |
|||
IUnitOfWorkManager unitOfWorkManager, |
|||
IEventHandlerInvoker eventHandlerInvoker) |
|||
: base(options, serviceScopeFactory, currentTenant, unitOfWorkManager, eventHandlerInvoker) |
|||
{ |
|||
} |
|||
|
|||
protected override IEnumerable<EventTypeWithEventHandlerFactories> GetHandlerFactories(System.Type eventType) |
|||
{ |
|||
if (eventType == typeof(FilteredEventData)) |
|||
{ |
|||
FilteredCalls++; |
|||
return Enumerable.Empty<EventTypeWithEventHandlerFactories>(); |
|||
} |
|||
|
|||
return base.GetHandlerFactories(eventType); |
|||
} |
|||
} |
|||
} |
|||
|
|||
public class StateEventData |
|||
{ |
|||
} |
|||
|
|||
public class ConstructionState |
|||
{ |
|||
public int Value { get; set; } |
|||
|
|||
public int SeenByReader { get; set; } = -1; |
|||
} |
|||
|
|||
public class DisposeFailingStateHandler : ILocalEventHandler<StateEventData>, System.IDisposable |
|||
{ |
|||
private readonly ConstructionState _state; |
|||
|
|||
public DisposeFailingStateHandler(ConstructionState state) |
|||
{ |
|||
_state = state; |
|||
} |
|||
|
|||
public Task HandleEventAsync(StateEventData eventData) |
|||
{ |
|||
_state.Value++; |
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
public void Dispose() |
|||
{ |
|||
throw new System.InvalidOperationException("Dispose failed."); |
|||
} |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(-1)] |
|||
public class StateWritingHandler : ILocalEventHandler<StateEventData> |
|||
{ |
|||
private readonly ConstructionState _state; |
|||
|
|||
public StateWritingHandler(ConstructionState state) |
|||
{ |
|||
_state = state; |
|||
} |
|||
|
|||
public Task HandleEventAsync(StateEventData eventData) |
|||
{ |
|||
_state.Value = 42; |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(1)] |
|||
public class StateReadingHandler : ILocalEventHandler<StateEventData> |
|||
{ |
|||
private readonly ConstructionState _state; |
|||
private readonly int _valueWhenCreated; |
|||
|
|||
public StateReadingHandler(ConstructionState state) |
|||
{ |
|||
_state = state; |
|||
_valueWhenCreated = state.Value; |
|||
} |
|||
|
|||
public Task HandleEventAsync(StateEventData eventData) |
|||
{ |
|||
_state.SeenByReader = _valueWhenCreated; |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
@ -0,0 +1,620 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Autofac; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Options; |
|||
using Shouldly; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.DynamicProxy; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Volo.Abp.Uow; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.EventBus.Local; |
|||
|
|||
/// <summary>
|
|||
/// An IoC handler whose registration tells its type is ordered by that type, so it is created only to handle the event.
|
|||
/// </summary>
|
|||
public class LocalEventBus_RegisteredHandlerType_Tests : EventBusTestBase |
|||
{ |
|||
protected override void AfterAddApplication(IServiceCollection services) |
|||
{ |
|||
// Registered with Autofac directly: registered through the service collection, they would also be subscribed
|
|||
// to the application's bus by convention.
|
|||
var builder = services.GetObject<ContainerBuilder>(); |
|||
builder.RegisterType<Tracker>().SingleInstance(); |
|||
builder.RegisterType<TrackedDependency>().InstancePerLifetimeScope(); |
|||
builder.RegisterType<ConstructionState>().SingleInstance(); |
|||
builder.RegisterType<FirstHandler>(); |
|||
builder.RegisterType<SecondHandler>(); |
|||
builder.RegisterType<ReplacementOfReplacedHandler>().As<ReplacedHandler>(); |
|||
builder.Register(context => context.Resolve<Tracker>().CreateReplacement |
|||
? new ReplacementOfSwitchedHandler(context.Resolve<TrackedDependency>()) |
|||
: new SwitchedHandler(context.Resolve<TrackedDependency>())) |
|||
.As<SwitchedHandler>(); |
|||
builder.RegisterType<ActivatedHandler>() |
|||
.OnActivating(e => e.ReplaceInstance(new ReplacementOfActivatedHandler(e.Context.Resolve<TrackedDependency>()))); |
|||
builder.RegisterType<ThrowingWhileHandlingHandler>(); |
|||
builder.RegisterType<ConstructionFailingHandler>(); |
|||
builder.RegisterType<DynamicHandler>(); |
|||
builder.RegisterType<OuterHandler>(); |
|||
builder.RegisterType<InnerHandler>(); |
|||
builder.RegisterType<NamedDynamicHandler>(); |
|||
builder.RegisterType<NamedTypedHandler>(); |
|||
builder.RegisterType<StateWritingHandler>(); |
|||
builder.RegisterType<StateReadingHandler>(); |
|||
|
|||
services.OnRegistered(context => |
|||
{ |
|||
if (context.ImplementationType == typeof(InterceptedHandler)) |
|||
{ |
|||
context.Interceptors.TryAdd<CountingInterceptor>(); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task An_Ioc_Handler_Should_Be_Created_Once_Per_Publish() |
|||
{ |
|||
var tracker = GetRequiredService<Tracker>(); |
|||
using (Subscribe<RegisteredTypeEventData, SecondHandler>()) |
|||
{ |
|||
for (var i = 0; i < 3; i++) |
|||
{ |
|||
await LocalEventBus.PublishAsync(new RegisteredTypeEventData()); |
|||
} |
|||
} |
|||
|
|||
tracker.Log.Count.ShouldBe(3); |
|||
tracker.Created.ShouldBe(3); |
|||
tracker.Disposed.ShouldBe(3); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Replaced_Ioc_Handler_Should_Be_Ordered_By_The_Replacement_And_Created_Once() |
|||
{ |
|||
var tracker = GetRequiredService<Tracker>(); |
|||
using (Subscribe<RegisteredTypeEventData, FirstHandler>()) |
|||
using (Subscribe<RegisteredTypeEventData, ReplacedHandler>()) |
|||
{ |
|||
await LocalEventBus.PublishAsync(new RegisteredTypeEventData()); |
|||
} |
|||
|
|||
tracker.Log.ShouldBe(new[] { "replacement", "first disposed=1" }); |
|||
tracker.Created.ShouldBe(2); |
|||
tracker.Disposed.ShouldBe(2); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Handler_Registered_With_A_Factory_Method_Should_Be_Ordered_By_What_It_Creates_On_Each_Publish() |
|||
{ |
|||
var tracker = GetRequiredService<Tracker>(); |
|||
using (Subscribe<RegisteredTypeEventData, FirstHandler>()) |
|||
using (Subscribe<RegisteredTypeEventData, SwitchedHandler>()) |
|||
{ |
|||
await LocalEventBus.PublishAsync(new RegisteredTypeEventData()); |
|||
tracker.Log.ShouldBe(new[] { "first disposed=1", "switched" }); |
|||
|
|||
tracker.CreateReplacement = true; |
|||
tracker.Log.Clear(); |
|||
await LocalEventBus.PublishAsync(new RegisteredTypeEventData()); |
|||
tracker.Log.ShouldBe(new[] { "switched replacement", "first disposed=5" }); |
|||
} |
|||
|
|||
// Its type can only be read from a handler, which is created to read it on each publish.
|
|||
tracker.Created.ShouldBe(6); |
|||
tracker.Disposed.ShouldBe(6); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Handler_Replaced_When_Activated_Should_Be_Ordered_By_What_Is_Created_From_Then_On() |
|||
{ |
|||
var tracker = GetRequiredService<Tracker>(); |
|||
using (Subscribe<RegisteredTypeEventData, FirstHandler>()) |
|||
using (Subscribe<RegisteredTypeEventData, ActivatedHandler>()) |
|||
{ |
|||
// The registration can not tell the replacement, so the first publish orders by the registered type.
|
|||
await LocalEventBus.PublishAsync(new RegisteredTypeEventData()); |
|||
tracker.Log.ShouldBe(new[] { "first disposed=0", "activated replacement" }); |
|||
|
|||
// Having created another type, the factory reads the type from a handler from then on.
|
|||
tracker.Log.Clear(); |
|||
await LocalEventBus.PublishAsync(new RegisteredTypeEventData()); |
|||
tracker.Log.ShouldBe(new[] { "activated replacement", "first disposed=4" }); |
|||
} |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Later_Handler_Should_Be_Created_After_An_Earlier_One_Ran() |
|||
{ |
|||
var state = GetRequiredService<ConstructionState>(); |
|||
using (Subscribe<StateEventData, StateReadingHandler>()) |
|||
using (Subscribe<StateEventData, StateWritingHandler>()) |
|||
{ |
|||
for (var i = 0; i < 2; i++) |
|||
{ |
|||
state.Value = 0; |
|||
state.SeenByReader = -1; |
|||
|
|||
await LocalEventBus.PublishAsync(new StateEventData()); |
|||
|
|||
state.SeenByReader.ShouldBe(42); |
|||
} |
|||
} |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Each_Handler_Should_Release_Its_Scope_Before_The_Next_One_Runs() |
|||
{ |
|||
var tracker = GetRequiredService<Tracker>(); |
|||
using (Subscribe<RegisteredTypeEventData, SecondHandler>()) |
|||
using (Subscribe<RegisteredTypeEventData, FirstHandler>()) |
|||
{ |
|||
await LocalEventBus.PublishAsync(new RegisteredTypeEventData()); |
|||
} |
|||
|
|||
tracker.Log.ShouldBe(new[] { "first disposed=0", "second disposed=1" }); |
|||
tracker.Created.ShouldBe(2); |
|||
tracker.Disposed.ShouldBe(2); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Handler_That_Throws_Should_Not_Stop_The_Next_One_Or_Keep_Any_Scope() |
|||
{ |
|||
var tracker = GetRequiredService<Tracker>(); |
|||
using (Subscribe<RegisteredTypeEventData, SecondHandler>()) |
|||
using (Subscribe<RegisteredTypeEventData, ThrowingWhileHandlingHandler>()) |
|||
{ |
|||
(await Should.ThrowAsync<InvalidOperationException>(() => LocalEventBus.PublishAsync(new RegisteredTypeEventData()))) |
|||
.Message.ShouldBe("Handling failed."); |
|||
} |
|||
|
|||
tracker.Log.ShouldBe(new[] { "throwing", "second disposed=1" }); |
|||
tracker.Created.ShouldBe(2); |
|||
tracker.Disposed.ShouldBe(2); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Handler_That_Fails_To_Construct_Should_Stop_The_Publish_After_The_Earlier_Ones_Ran() |
|||
{ |
|||
var tracker = GetRequiredService<Tracker>(); |
|||
using (Subscribe<RegisteredTypeEventData, FirstHandler>()) |
|||
using (Subscribe<RegisteredTypeEventData, ConstructionFailingHandler>()) |
|||
using (Subscribe<RegisteredTypeEventData, SecondHandler>()) |
|||
{ |
|||
(await Should.ThrowAsync<Exception>(() => LocalEventBus.PublishAsync(new RegisteredTypeEventData()))) |
|||
.GetBaseException().Message.ShouldBe("Construction failed."); |
|||
} |
|||
|
|||
tracker.Log.ShouldBe(new[] { "first disposed=0" }); |
|||
tracker.Created.ShouldBe(2); |
|||
tracker.Disposed.ShouldBe(2); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Dynamic_Ioc_Handler_Should_Be_Created_Once_Per_Publish() |
|||
{ |
|||
var tracker = GetRequiredService<Tracker>(); |
|||
var eventName = "RegisteredTypeDynamic-" + Guid.NewGuid().ToString("N"); |
|||
using (LocalEventBus.Subscribe(eventName, CreateFactory<DynamicHandler>())) |
|||
{ |
|||
await LocalEventBus.PublishAsync(eventName, new { Value = 1 }); |
|||
} |
|||
|
|||
tracker.Log.ShouldBe(new[] { "dynamic" }); |
|||
tracker.Created.ShouldBe(1); |
|||
tracker.Disposed.ShouldBe(1); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Publish_Stopped_Before_A_Handler_Should_Not_Create_It() |
|||
{ |
|||
var tracker = GetRequiredService<Tracker>(); |
|||
using (LocalEventBus.Subscribe(typeof(NamedEventData), CreateFactory<NamedTypedHandler>())) |
|||
using (LocalEventBus.Subscribe(NamedEventData.Name, CreateFactory<NamedDynamicHandler>())) |
|||
{ |
|||
// The typed handler's data cannot be converted, which ends the publish after the dynamic handler ran.
|
|||
await Should.ThrowAsync<Exception>(() => ((LocalEventBus)LocalEventBus).TriggerHandlersAsync( |
|||
typeof(DynamicEventData), |
|||
new DynamicEventData(NamedEventData.Name, new { Value = "not a number" }))); |
|||
} |
|||
|
|||
tracker.Log.ShouldBe(new[] { "named dynamic" }); |
|||
tracker.Created.ShouldBe(1); |
|||
tracker.Disposed.ShouldBe(1); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Publish_From_A_Handler_Should_Create_And_Release_Its_Own_Handlers() |
|||
{ |
|||
var tracker = GetRequiredService<Tracker>(); |
|||
using (Subscribe<RegisteredTypeEventData, OuterHandler>()) |
|||
using (Subscribe<InnerEventData, InnerHandler>()) |
|||
{ |
|||
await LocalEventBus.PublishAsync(new RegisteredTypeEventData()); |
|||
} |
|||
|
|||
tracker.Log.ShouldBe(new[] { "inner disposed=0", "outer done" }); |
|||
tracker.Created.ShouldBe(2); |
|||
tracker.Disposed.ShouldBe(2); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task An_Intercepted_Handler_Should_Be_Created_Once_Per_Publish() |
|||
{ |
|||
InterceptedHandler.Reset(); |
|||
CountingInterceptor.Reset(); |
|||
|
|||
for (var i = 0; i < 2; i++) |
|||
{ |
|||
await LocalEventBus.PublishAsync(new InterceptedEventData()); |
|||
} |
|||
|
|||
// The registration creates a class proxy, the type every handler it creates has.
|
|||
InterceptedHandler.Created.ShouldBe(2); |
|||
InterceptedHandler.Handled.ShouldBe(2); |
|||
CountingInterceptor.Intercepted.ShouldBe(2); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task A_Derived_Bus_Should_Order_By_The_Registered_Type_Too() |
|||
{ |
|||
var tracker = GetRequiredService<Tracker>(); |
|||
var derived = ActivatorUtilities.CreateInstance<DerivedLocalEventBus>(ServiceProvider); |
|||
using (derived.Subscribe(typeof(RegisteredTypeEventData), CreateFactory<FirstHandler>())) |
|||
using (derived.Subscribe(typeof(RegisteredTypeEventData), CreateFactory<ReplacedHandler>())) |
|||
{ |
|||
await derived.PublishAsync(new RegisteredTypeEventData(), onUnitOfWorkComplete: false); |
|||
} |
|||
|
|||
tracker.Log.ShouldBe(new[] { "replacement", "first disposed=1" }); |
|||
tracker.Created.ShouldBe(2); |
|||
tracker.Disposed.ShouldBe(2); |
|||
} |
|||
|
|||
private IDisposable Subscribe<TEvent, THandler>() |
|||
{ |
|||
return LocalEventBus.Subscribe(typeof(TEvent), CreateFactory<THandler>()); |
|||
} |
|||
|
|||
private IocEventHandlerFactory CreateFactory<THandler>() |
|||
{ |
|||
return new IocEventHandlerFactory(GetRequiredService<IServiceScopeFactory>(), typeof(THandler)); |
|||
} |
|||
|
|||
public class RegisteredTypeEventData |
|||
{ |
|||
} |
|||
|
|||
public class InnerEventData |
|||
{ |
|||
} |
|||
|
|||
public class InterceptedEventData |
|||
{ |
|||
} |
|||
|
|||
[EventName(Name)] |
|||
public class NamedEventData |
|||
{ |
|||
public const string Name = "Volo.Abp.EventBus.Local.LocalEventBus_RegisteredHandlerType_Tests.Named"; |
|||
|
|||
public int Value { get; set; } |
|||
} |
|||
|
|||
public class Tracker |
|||
{ |
|||
private int _created; |
|||
private int _disposed; |
|||
|
|||
public List<string> Log { get; } = new(); |
|||
|
|||
public bool CreateReplacement { get; set; } |
|||
|
|||
public int Created => _created; |
|||
|
|||
public int Disposed => _disposed; |
|||
|
|||
public void OnCreated() => Interlocked.Increment(ref _created); |
|||
|
|||
public void OnDisposed() => Interlocked.Increment(ref _disposed); |
|||
} |
|||
|
|||
public class TrackedDependency : IDisposable |
|||
{ |
|||
public Tracker Tracker { get; } |
|||
|
|||
public TrackedDependency(Tracker tracker) |
|||
{ |
|||
Tracker = tracker; |
|||
Tracker.OnCreated(); |
|||
} |
|||
|
|||
public void Dispose() |
|||
{ |
|||
Tracker.OnDisposed(); |
|||
} |
|||
} |
|||
|
|||
public abstract class TrackedHandler : ILocalEventHandler<RegisteredTypeEventData> |
|||
{ |
|||
protected TrackedDependency Dependency { get; } |
|||
|
|||
protected TrackedHandler(TrackedDependency dependency) |
|||
{ |
|||
Dependency = dependency; |
|||
} |
|||
|
|||
public virtual Task HandleEventAsync(RegisteredTypeEventData eventData) |
|||
{ |
|||
Dependency.Tracker.Log.Add(GetLogEntry()); |
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
protected abstract string GetLogEntry(); |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(-1)] |
|||
public class FirstHandler : TrackedHandler |
|||
{ |
|||
public FirstHandler(TrackedDependency dependency) |
|||
: base(dependency) |
|||
{ |
|||
} |
|||
|
|||
protected override string GetLogEntry() => $"first disposed={Dependency.Tracker.Disposed}"; |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(1)] |
|||
public class SecondHandler : TrackedHandler |
|||
{ |
|||
public SecondHandler(TrackedDependency dependency) |
|||
: base(dependency) |
|||
{ |
|||
} |
|||
|
|||
protected override string GetLogEntry() => $"second disposed={Dependency.Tracker.Disposed}"; |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(1)] |
|||
public class ReplacedHandler : TrackedHandler |
|||
{ |
|||
public ReplacedHandler(TrackedDependency dependency) |
|||
: base(dependency) |
|||
{ |
|||
} |
|||
|
|||
protected override string GetLogEntry() => "replaced"; |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(-10)] |
|||
public class ReplacementOfReplacedHandler : ReplacedHandler |
|||
{ |
|||
public ReplacementOfReplacedHandler(TrackedDependency dependency) |
|||
: base(dependency) |
|||
{ |
|||
} |
|||
|
|||
protected override string GetLogEntry() => "replacement"; |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(1)] |
|||
public class SwitchedHandler : TrackedHandler |
|||
{ |
|||
public SwitchedHandler(TrackedDependency dependency) |
|||
: base(dependency) |
|||
{ |
|||
} |
|||
|
|||
protected override string GetLogEntry() => "switched"; |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(-10)] |
|||
public class ReplacementOfSwitchedHandler : SwitchedHandler |
|||
{ |
|||
public ReplacementOfSwitchedHandler(TrackedDependency dependency) |
|||
: base(dependency) |
|||
{ |
|||
} |
|||
|
|||
protected override string GetLogEntry() => "switched replacement"; |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(1)] |
|||
public class ActivatedHandler : TrackedHandler |
|||
{ |
|||
public ActivatedHandler(TrackedDependency dependency) |
|||
: base(dependency) |
|||
{ |
|||
} |
|||
|
|||
protected override string GetLogEntry() => "activated"; |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(-10)] |
|||
public class ReplacementOfActivatedHandler : ActivatedHandler |
|||
{ |
|||
public ReplacementOfActivatedHandler(TrackedDependency dependency) |
|||
: base(dependency) |
|||
{ |
|||
} |
|||
|
|||
protected override string GetLogEntry() => "activated replacement"; |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(-1)] |
|||
public class ThrowingWhileHandlingHandler : TrackedHandler |
|||
{ |
|||
public ThrowingWhileHandlingHandler(TrackedDependency dependency) |
|||
: base(dependency) |
|||
{ |
|||
} |
|||
|
|||
public override Task HandleEventAsync(RegisteredTypeEventData eventData) |
|||
{ |
|||
base.HandleEventAsync(eventData); |
|||
throw new InvalidOperationException("Handling failed."); |
|||
} |
|||
|
|||
protected override string GetLogEntry() => "throwing"; |
|||
} |
|||
|
|||
public class ConstructionFailingHandler : ILocalEventHandler<RegisteredTypeEventData> |
|||
{ |
|||
public ConstructionFailingHandler(TrackedDependency dependency) |
|||
{ |
|||
throw new InvalidOperationException("Construction failed."); |
|||
} |
|||
|
|||
public Task HandleEventAsync(RegisteredTypeEventData eventData) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
public class DynamicHandler : ILocalEventHandler<DynamicEventData> |
|||
{ |
|||
private readonly TrackedDependency _dependency; |
|||
|
|||
public DynamicHandler(TrackedDependency dependency) |
|||
{ |
|||
_dependency = dependency; |
|||
} |
|||
|
|||
public Task HandleEventAsync(DynamicEventData eventData) |
|||
{ |
|||
_dependency.Tracker.Log.Add("dynamic"); |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
public class OuterHandler : ILocalEventHandler<RegisteredTypeEventData> |
|||
{ |
|||
private readonly TrackedDependency _dependency; |
|||
private readonly ILocalEventBus _localEventBus; |
|||
|
|||
public OuterHandler(TrackedDependency dependency, ILocalEventBus localEventBus) |
|||
{ |
|||
_dependency = dependency; |
|||
_localEventBus = localEventBus; |
|||
} |
|||
|
|||
public async Task HandleEventAsync(RegisteredTypeEventData eventData) |
|||
{ |
|||
await _localEventBus.PublishAsync(new InnerEventData(), onUnitOfWorkComplete: false); |
|||
_dependency.Tracker.Log.Add("outer done"); |
|||
} |
|||
} |
|||
|
|||
public class InnerHandler : ILocalEventHandler<InnerEventData> |
|||
{ |
|||
private readonly TrackedDependency _dependency; |
|||
|
|||
public InnerHandler(TrackedDependency dependency) |
|||
{ |
|||
_dependency = dependency; |
|||
} |
|||
|
|||
public Task HandleEventAsync(InnerEventData eventData) |
|||
{ |
|||
_dependency.Tracker.Log.Add($"inner disposed={_dependency.Tracker.Disposed}"); |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(-1)] |
|||
public class NamedDynamicHandler : ILocalEventHandler<DynamicEventData> |
|||
{ |
|||
private readonly TrackedDependency _dependency; |
|||
|
|||
public NamedDynamicHandler(TrackedDependency dependency) |
|||
{ |
|||
_dependency = dependency; |
|||
} |
|||
|
|||
public Task HandleEventAsync(DynamicEventData eventData) |
|||
{ |
|||
_dependency.Tracker.Log.Add("named dynamic"); |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
[LocalEventHandlerOrder(1)] |
|||
public class NamedTypedHandler : ILocalEventHandler<NamedEventData> |
|||
{ |
|||
private readonly TrackedDependency _dependency; |
|||
|
|||
public NamedTypedHandler(TrackedDependency dependency) |
|||
{ |
|||
_dependency = dependency; |
|||
} |
|||
|
|||
public Task HandleEventAsync(NamedEventData eventData) |
|||
{ |
|||
_dependency.Tracker.Log.Add("named typed"); |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
public class InterceptedHandler : ILocalEventHandler<InterceptedEventData>, ITransientDependency |
|||
{ |
|||
private static int _created; |
|||
private static int _handled; |
|||
|
|||
public static int Created => _created; |
|||
|
|||
public static int Handled => _handled; |
|||
|
|||
public InterceptedHandler() |
|||
{ |
|||
Interlocked.Increment(ref _created); |
|||
} |
|||
|
|||
public static void Reset() |
|||
{ |
|||
_created = 0; |
|||
_handled = 0; |
|||
} |
|||
|
|||
public virtual Task HandleEventAsync(InterceptedEventData eventData) |
|||
{ |
|||
Interlocked.Increment(ref _handled); |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
public class CountingInterceptor : AbpInterceptor, ITransientDependency |
|||
{ |
|||
private static int _intercepted; |
|||
|
|||
public static int Intercepted => _intercepted; |
|||
|
|||
public static void Reset() |
|||
{ |
|||
_intercepted = 0; |
|||
} |
|||
|
|||
public override async Task InterceptAsync(IAbpMethodInvocation invocation) |
|||
{ |
|||
Interlocked.Increment(ref _intercepted); |
|||
await invocation.ProceedAsync(); |
|||
} |
|||
} |
|||
|
|||
// Kept out of conventional registration, which would make it the application's bus.
|
|||
[DisableConventionalRegistration] |
|||
public class DerivedLocalEventBus : LocalEventBus |
|||
{ |
|||
public DerivedLocalEventBus( |
|||
IOptions<AbpLocalEventBusOptions> options, |
|||
IServiceScopeFactory serviceScopeFactory, |
|||
ICurrentTenant currentTenant, |
|||
IUnitOfWorkManager unitOfWorkManager, |
|||
IEventHandlerInvoker eventHandlerInvoker) |
|||
: base(options, serviceScopeFactory, currentTenant, unitOfWorkManager, eventHandlerInvoker) |
|||
{ |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue