Browse Source

Order IoC event handlers by the handler created on each publish

- Keep the proxy interface order for types that implement a variant interface more than once
pull/26263/head
maliming 1 week ago
parent
commit
4122409b2c
No known key found for this signature in database GPG Key ID: A646B9CB645ECEA4
  1. 16
      framework/src/Volo.Abp.Autofac/Autofac/Builder/AbpInterceptionRegistrationExtensions.cs
  2. 45
      framework/src/Volo.Abp.Autofac/Volo/Abp/Autofac/AutofacServiceImplementationTypeProvider.cs
  3. 13
      framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/IServiceImplementationTypeProvider.cs
  4. 12
      framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/NullServiceImplementationTypeProvider.cs
  5. 40
      framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/IocEventHandlerFactory.cs
  6. 12
      framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Local/LocalEventBus.cs
  7. 138
      framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/AutofacServiceImplementationTypeProvider_Tests.cs
  8. 30
      framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interface_Interception_Test.cs
  9. 72
      framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_RegisteredHandlerType_Tests.cs
  10. 3
      framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/EventBusTestModule.cs
  11. 42
      framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/EventBus_Order_Test.cs
  12. 4
      framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/IocEventHandlerFactory_Tests.cs
  13. 620
      framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/LocalEventBus_RegisteredHandlerType_Tests.cs

16
framework/src/Volo.Abp.Autofac/Autofac/Builder/AbpInterceptionRegistrationExtensions.cs

@ -166,7 +166,9 @@ public static class AbpInterceptionRegistrationExtensions
/// 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.
/// configured to copy. It is not preferred either when the type implements a variant generic interface more than
/// once, since a call through a variant interface that matches several of them runs the first one in the proxy's
/// interface order.
/// </remarks>
private sealed class ProxiedInterfaceSet
{
@ -185,7 +187,8 @@ public static class AbpInterceptionRegistrationExtensions
var primary = interfaces[0];
var own = interfaces.FirstOrDefault(i => i.Name == "I" + type.Name);
if (own != null && own != primary && !HasPublicAttributes(primary) && !HasPublicAttributes(own))
if (own != null && own != primary && !HasPublicAttributes(primary) && !HasPublicAttributes(own) &&
!ImplementsAVariantInterfaceMoreThanOnce(interfaces))
{
primary = own;
}
@ -209,6 +212,15 @@ public static class AbpInterceptionRegistrationExtensions
(attribute.AttributeType.IsPublic || attribute.AttributeType.IsNestedPublic) &&
!NullableAnnotations.Contains(attribute.AttributeType.FullName));
}
private static bool ImplementsAVariantInterfaceMoreThanOnce(Type[] interfaces)
{
return interfaces
.Where(i => i.IsGenericType && i.GetGenericTypeDefinition().GetGenericArguments()
.Any(argument => (argument.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) != 0))
.GroupBy(i => i.GetGenericTypeDefinition())
.Any(group => group.Count() > 1);
}
}
private static void EnsureInterfaceInterceptionApplies(IComponentRegistration componentRegistration)

45
framework/src/Volo.Abp.Autofac/Volo/Abp/Autofac/AutofacServiceImplementationTypeProvider.cs

@ -1,45 +0,0 @@
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;
}
}

13
framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/IServiceImplementationTypeProvider.cs

@ -1,13 +0,0 @@
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);
}

12
framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/NullServiceImplementationTypeProvider.cs

@ -1,12 +0,0 @@
using System;
namespace Volo.Abp.DependencyInjection;
[Dependency(TryRegister = true)]
public class NullServiceImplementationTypeProvider : IServiceImplementationTypeProvider, ITransientDependency
{
public Type? GetImplementationTypeOrNull(Type serviceType)
{
return null;
}
}

40
framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/IocEventHandlerFactory.cs

@ -1,10 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.DependencyInjection;
namespace Volo.Abp.EventBus;
@ -18,8 +15,6 @@ public class IocEventHandlerFactory : IEventHandlerFactory, IDisposable
protected IServiceScopeFactory ScopeFactory { get; }
private StrongBox<Type?>? _implementationType;
public IocEventHandlerFactory(IServiceScopeFactory scopeFactory, Type handlerType)
{
ScopeFactory = scopeFactory;
@ -36,14 +31,6 @@ public class IocEventHandlerFactory : IEventHandlerFactory, IDisposable
try
{
var handler = (IEventHandler)scope.ServiceProvider.GetRequiredService(HandlerType);
var implementationType = Volatile.Read(ref _implementationType)?.Value;
if (implementationType != null && implementationType != handler.GetType())
{
// The container created another type than its registration told, so it is not asked again.
Volatile.Write(ref _implementationType, new StrongBox<Type?>(null));
}
return new EventHandlerDisposeWrapper(handler, () => scope.Dispose());
}
catch
@ -61,33 +48,6 @@ public class IocEventHandlerFactory : IEventHandlerFactory, IDisposable
}
}
/// <summary>
/// Gets the type of the handlers this factory creates when the container can tell it without creating one,
/// otherwise null. The container is asked once.
/// </summary>
internal Type? GetImplementationTypeOrNull()
{
var implementationType = Volatile.Read(ref _implementationType);
if (implementationType == null)
{
// Never replaces what GetHandler wrote meanwhile.
Interlocked.CompareExchange(ref _implementationType, new StrongBox<Type?>(FindImplementationType()), null);
implementationType = Volatile.Read(ref _implementationType)!;
}
return implementationType.Value;
}
private Type? FindImplementationType()
{
using (var scope = ScopeFactory.CreateScope())
{
return scope.ServiceProvider
.GetService<IServiceImplementationTypeProvider>()?
.GetImplementationTypeOrNull(HandlerType);
}
}
public bool IsInFactories(List<IEventHandlerFactory> handlerFactories)
{
return handlerFactories

12
framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Local/LocalEventBus.cs

@ -284,9 +284,9 @@ public class LocalEventBus : EventBusBase, ILocalEventBus, ISingletonDependency
/// <summary>
/// Gets the <see cref="LocalEventHandlerOrderAttribute"/> order of the handler the factory creates.
/// When the handler type is known without creating a handler (the built-in factories of a fixed type, and an
/// IoC handler whose registration in the container fixes its type), the order is read from that type.
/// Otherwise the handler is created to read its type and is disposed at once, on each publish. Callers
/// When the handler type is known without creating a handler (the built-in factories of a fixed type), the order
/// is read from that type. Otherwise the handler is created to read its type and is disposed at once, on each
/// publish, since what the container creates for a handler can change from one resolve to another. Callers
/// enumerate a snapshot of the factories, since that dispose runs handler code which may unsubscribe.
/// </summary>
protected virtual int GetHandlerOrder(IEventHandlerFactory factory)
@ -334,12 +334,6 @@ public class LocalEventBus : EventBusBase, ILocalEventBus, ISingletonDependency
return ((TransientEventHandlerFactory)factory).HandlerType;
}
// Only the built-in IoC factory, for the same reason.
if (factoryType == typeof(IocEventHandlerFactory))
{
return ((IocEventHandlerFactory)factory).GetImplementationTypeOrNull();
}
return null;
}

138
framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/AutofacServiceImplementationTypeProvider_Tests.cs

@ -1,138 +0,0 @@
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();
}
}
}

30
framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interface_Interception_Test.cs

@ -24,9 +24,11 @@ public class Autofac_Interface_Interception_Test : AbpAsyncIntegratedTest<Autofa
{
services.AddTransient<SimpleAsyncInterceptor>();
services.AddTransient<IInterfaceInterceptionTarget, InterfaceInterceptionTarget>();
services.AddTransient<IVariantTarget, VariantTarget>();
services.OnRegistered(registration =>
{
if (typeof(InterfaceInterceptionTarget) == registration.ImplementationType)
if (typeof(InterfaceInterceptionTarget) == registration.ImplementationType ||
typeof(VariantTarget) == registration.ImplementationType)
{
registration.Interceptors.Add<SimpleAsyncInterceptor>();
}
@ -68,6 +70,32 @@ public class Autofac_Interface_Interception_Test : AbpAsyncIntegratedTest<Autofa
target.GetType().ShouldBeSameAs(proxyType);
}
[Fact]
public void A_Call_Through_A_Variant_Interface_Should_Run_What_The_Target_Runs()
{
var target = GetRequiredService<IVariantTarget>();
ProxyUtil.IsProxy(target).ShouldBeTrue();
// IVariant<object> matches both IVariant<string> and IVariant<Version>, so the interface order decides which runs.
((IVariant<object>)target).Get().ShouldBe(((IVariant<object>)ProxyUtil.GetUnproxiedInstance(target)).Get());
}
public interface IVariant<out T>
{
T Get();
}
public interface IVariantTarget : IVariant<Version>
{
}
public class VariantTarget : IVariant<string>, IVariantTarget
{
string IVariant<string>.Get() => "string";
Version IVariant<Version>.Get() => new Version(1, 0);
}
public interface IInterfaceInterceptionTarget : ICanLogOnObject
{
Task<int> GetValueAsync();

72
framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_RegisteredHandlerType_Tests.cs

@ -1,72 +0,0 @@
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;
}
}
}

3
framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/EventBusTestModule.cs

@ -1,9 +1,8 @@
using Volo.Abp.Autofac;
using Volo.Abp.Modularity;
namespace Volo.Abp.EventBus;
[DependsOn(typeof(AbpEventBusModule), typeof(AbpAutofacModule))]
[DependsOn(typeof(AbpEventBusModule))]
public class EventBusTestModule : AbpModule
{
}

42
framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/EventBus_Order_Test.cs

@ -23,7 +23,7 @@ public class EventBus_Order_Test : EventBusTestBase
}
[Fact]
public async Task An_Ioc_Handler_Should_Be_Created_Once_Per_Publish()
public async Task An_Ioc_Handler_Created_To_Read_Its_Order_Should_Be_Disposed()
{
CountedOrderEventHandler.Reset();
@ -32,22 +32,22 @@ public class EventBus_Order_Test : EventBusTestBase
await LocalEventBus.PublishAsync(new CountedOrderEventData());
}
// Its registration tells its type, so it is not created to read its order.
CountedOrderEventHandler.Created.ShouldBe(3);
// Each publish creates the handler once to read its order and once to handle the event.
CountedOrderEventHandler.Created.ShouldBe(6);
CountedOrderEventHandler.Handled.ShouldBe(3);
CountedOrderEventHandler.Disposed.ShouldBe(3);
CountedOrderEventHandler.Disposed.ShouldBe(6);
}
[Fact]
public void Listing_The_Factories_Should_Return_The_Subscribed_Factories_Without_Creating_A_Handler()
public void Listing_The_Factories_Should_Dispose_The_Handlers_Created_To_Read_Their_Order()
{
CountedOrderEventHandler.Reset();
var factories = ((LocalEventBus)LocalEventBus).GetEventHandlerFactories(typeof(CountedOrderEventData));
factories.SelectMany(x => x.EventHandlerFactories).ShouldContain(x => x is IocEventHandlerFactory);
CountedOrderEventHandler.Created.ShouldBe(0);
CountedOrderEventHandler.Disposed.ShouldBe(0);
CountedOrderEventHandler.Created.ShouldBe(1);
CountedOrderEventHandler.Disposed.ShouldBe(1);
CountedOrderEventHandler.Handled.ShouldBe(0);
}
@ -168,7 +168,7 @@ public class EventBus_Order_Test : EventBusTestBase
}
[Fact]
public async Task An_Ioc_Handler_Replaced_In_A_Container_That_Can_Not_Tell_Its_Type_Should_Be_Ordered_By_The_Replacement()
public async Task An_Ioc_Handler_Replaced_In_The_Container_Should_Be_Ordered_By_The_Replacement()
{
var services = new ServiceCollection();
services.AddTransient<OriginalIocOrderEventHandler, ReplacementIocOrderEventHandler>();
@ -183,11 +183,35 @@ public class EventBus_Order_Test : EventBusTestBase
}
HandlerExecuteOrder.ShouldBe("R0");
// Microsoft's container does not tell the type, so the handler is also created to read its order.
// The handler is also created to read its order.
ReplacementIocOrderEventHandler.Created.ShouldBe(2);
ReplacementIocOrderEventHandler.Disposed.ShouldBe(2);
}
[Fact]
public async Task An_Ioc_Handler_Should_Be_Ordered_By_The_Type_The_Container_Creates_On_Each_Publish()
{
var createReplacement = false;
var services = new ServiceCollection();
services.AddTransient<OriginalIocOrderEventHandler>(_ => createReplacement
? new ReplacementIocOrderEventHandler()
: new OriginalIocOrderEventHandler());
await using var provider = services.BuildServiceProvider();
using (LocalEventBus.Subscribe<IocReplacedOrderEventData, ZeroOrderIocEventHandler>())
using (LocalEventBus.Subscribe(typeof(IocReplacedOrderEventData), new IocEventHandlerFactory(provider.GetRequiredService<IServiceScopeFactory>(), typeof(OriginalIocOrderEventHandler))))
{
HandlerExecuteOrder = "";
await LocalEventBus.PublishAsync(new IocReplacedOrderEventData());
HandlerExecuteOrder.ShouldBe("0O");
createReplacement = true;
HandlerExecuteOrder = "";
await LocalEventBus.PublishAsync(new IocReplacedOrderEventData());
HandlerExecuteOrder.ShouldBe("R0");
}
}
[Fact]
public async Task Publishing_While_Others_Subscribe_And_Unsubscribe_Should_Not_Fail()
{

4
framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/IocEventHandlerFactory_Tests.cs

@ -84,8 +84,8 @@ public class IocEventHandlerFactory_Tests : EventBusTestBase
[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.
// A Microsoft container of its own, so neither handler is also subscribed to the application's bus by convention.
// Both are created to read their order.
var services = new ServiceCollection();
AddThrowingHandler(services);
services.AddTransient<EarlierWorkingHandler>();

620
framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/LocalEventBus_RegisteredHandlerType_Tests.cs

@ -1,620 +0,0 @@
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…
Cancel
Save