diff --git a/framework/src/Volo.Abp.Autofac/Autofac/Builder/AbpInterceptionRegistrationExtensions.cs b/framework/src/Volo.Abp.Autofac/Autofac/Builder/AbpInterceptionRegistrationExtensions.cs index 52503f7abb..fcd7752fe0 100644 --- a/framework/src/Volo.Abp.Autofac/Autofac/Builder/AbpInterceptionRegistrationExtensions.cs +++ b/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. /// 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) diff --git a/framework/src/Volo.Abp.Autofac/Volo/Abp/Autofac/AutofacServiceImplementationTypeProvider.cs b/framework/src/Volo.Abp.Autofac/Volo/Abp/Autofac/AutofacServiceImplementationTypeProvider.cs deleted file mode 100644 index d0511a34f3..0000000000 --- a/framework/src/Volo.Abp.Autofac/Volo/Abp/Autofac/AutofacServiceImplementationTypeProvider.cs +++ /dev/null @@ -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; - } -} diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/IServiceImplementationTypeProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/IServiceImplementationTypeProvider.cs deleted file mode 100644 index 183ec7d15f..0000000000 --- a/framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/IServiceImplementationTypeProvider.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace Volo.Abp.DependencyInjection; - -public interface IServiceImplementationTypeProvider -{ - /// - /// Gets the type of every instance the container creates for , 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. - /// - Type? GetImplementationTypeOrNull(Type serviceType); -} diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/NullServiceImplementationTypeProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/NullServiceImplementationTypeProvider.cs deleted file mode 100644 index 5a676c22d2..0000000000 --- a/framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/NullServiceImplementationTypeProvider.cs +++ /dev/null @@ -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; - } -} diff --git a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/IocEventHandlerFactory.cs b/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/IocEventHandlerFactory.cs index 7a51a2f16f..14f522cd32 100644 --- a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/IocEventHandlerFactory.cs +++ b/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? _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(null)); - } - return new EventHandlerDisposeWrapper(handler, () => scope.Dispose()); } catch @@ -61,33 +48,6 @@ public class IocEventHandlerFactory : IEventHandlerFactory, IDisposable } } - /// - /// 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. - /// - internal Type? GetImplementationTypeOrNull() - { - var implementationType = Volatile.Read(ref _implementationType); - if (implementationType == null) - { - // Never replaces what GetHandler wrote meanwhile. - Interlocked.CompareExchange(ref _implementationType, new StrongBox(FindImplementationType()), null); - implementationType = Volatile.Read(ref _implementationType)!; - } - - return implementationType.Value; - } - - private Type? FindImplementationType() - { - using (var scope = ScopeFactory.CreateScope()) - { - return scope.ServiceProvider - .GetService()? - .GetImplementationTypeOrNull(HandlerType); - } - } - public bool IsInFactories(List handlerFactories) { return handlerFactories diff --git a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Local/LocalEventBus.cs b/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Local/LocalEventBus.cs index 9ac45bc546..32dfbc0ee0 100644 --- a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Local/LocalEventBus.cs +++ b/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Local/LocalEventBus.cs @@ -284,9 +284,9 @@ public class LocalEventBus : EventBusBase, ILocalEventBus, ISingletonDependency /// /// Gets the 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. /// 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; } diff --git a/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/AutofacServiceImplementationTypeProvider_Tests.cs b/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/AutofacServiceImplementationTypeProvider_Tests.cs deleted file mode 100644 index 503dad0b91..0000000000 --- a/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/AutofacServiceImplementationTypeProvider_Tests.cs +++ /dev/null @@ -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 -{ - protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options) - { - options.UseAutofac(); - } - - protected override void AfterAddApplication(IServiceCollection services) - { - services.AddTransient(); - services.AddTransient(); - services.OnRegistered(context => - { - if (context.ImplementationType == typeof(TypeProviderInterceptedService)) - { - context.Interceptors.TryAdd(); - } - }); - - var builder = services.GetObject(); - builder.RegisterType(); - builder.RegisterType().As(); - builder.Register(_ => new TypeProviderService()).As(); - builder.RegisterType().As(); - builder.RegisterType().As(); - builder.RegisterDecorator(); - } - - [Fact] - public void Should_Replace_The_Null_Provider() - { - GetRequiredService().ShouldBeOfType(); - } - - [Fact] - public void Should_Tell_The_Type_A_Registration_Creates() - { - var provider = GetRequiredService(); - - 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().GetImplementationTypeOrNull(typeof(TypeProviderInterceptedService)); - - type.ShouldNotBeNull(); - type.ShouldNotBe(typeof(TypeProviderInterceptedService)); - type.ShouldBe(GetRequiredService().GetType()); - } - - [Fact] - public void Should_Not_Tell_A_Type_It_Can_Not_Know() - { - var provider = GetRequiredService(); - - 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(); - 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(); - } - } -} diff --git a/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interface_Interception_Test.cs b/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interface_Interception_Test.cs index ec0b7987d9..dd2f40b128 100644 --- a/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interface_Interception_Test.cs +++ b/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(); services.AddTransient(); + services.AddTransient(); services.OnRegistered(registration => { - if (typeof(InterfaceInterceptionTarget) == registration.ImplementationType) + if (typeof(InterfaceInterceptionTarget) == registration.ImplementationType || + typeof(VariantTarget) == registration.ImplementationType) { registration.Interceptors.Add(); } @@ -68,6 +70,32 @@ public class Autofac_Interface_Interception_Test : AbpAsyncIntegratedTest(); + + ProxyUtil.IsProxy(target).ShouldBeTrue(); + // IVariant matches both IVariant and IVariant, so the interface order decides which runs. + ((IVariant)target).Get().ShouldBe(((IVariant)ProxyUtil.GetUnproxiedInstance(target)).Get()); + } + + public interface IVariant + { + T Get(); + } + + public interface IVariantTarget : IVariant + { + } + + public class VariantTarget : IVariant, IVariantTarget + { + string IVariant.Get() => "string"; + + Version IVariant.Get() => new Version(1, 0); + } + public interface IInterfaceInterceptionTarget : ICanLogOnObject { Task GetValueAsync(); diff --git a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_RegisteredHandlerType_Tests.cs b/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_RegisteredHandlerType_Tests.cs deleted file mode 100644 index b6a2852797..0000000000 --- a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_RegisteredHandlerType_Tests.cs +++ /dev/null @@ -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(); - builder.RegisterType().SingleInstance(); - builder.RegisterType(); - } - - [Fact] - public async Task A_Distributed_Ioc_Handler_Should_Be_Created_Once_Per_Publish() - { - var counter = GetRequiredService(); - var factory = new IocEventHandlerFactory(GetRequiredService(), 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 - { - private readonly CreationCounter _counter; - - public CountedDistributedEventHandler(CreationCounter counter) - { - _counter = counter; - _counter.OnCreated(); - } - - public Task HandleEventAsync(CountedDistributedEventData eventData) - { - _counter.OnHandled(); - return Task.CompletedTask; - } - } -} diff --git a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/EventBusTestModule.cs b/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/EventBusTestModule.cs index 4764bd0b85..45d32d63ed 100644 --- a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/EventBusTestModule.cs +++ b/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 { } diff --git a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/EventBus_Order_Test.cs b/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/EventBus_Order_Test.cs index 7674b59477..da49ef40ca 100644 --- a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/EventBus_Order_Test.cs +++ b/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(); @@ -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(_ => createReplacement + ? new ReplacementIocOrderEventHandler() + : new OriginalIocOrderEventHandler()); + await using var provider = services.BuildServiceProvider(); + + using (LocalEventBus.Subscribe()) + using (LocalEventBus.Subscribe(typeof(IocReplacedOrderEventData), new IocEventHandlerFactory(provider.GetRequiredService(), 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() { diff --git a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/IocEventHandlerFactory_Tests.cs b/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/IocEventHandlerFactory_Tests.cs index 87873413ab..311d6cc9f7 100644 --- a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/IocEventHandlerFactory_Tests.cs +++ b/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(); diff --git a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/LocalEventBus_RegisteredHandlerType_Tests.cs b/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/LocalEventBus_RegisteredHandlerType_Tests.cs deleted file mode 100644 index 7b4b87cd95..0000000000 --- a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Local/LocalEventBus_RegisteredHandlerType_Tests.cs +++ /dev/null @@ -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; - -/// -/// An IoC handler whose registration tells its type is ordered by that type, so it is created only to handle the event. -/// -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(); - builder.RegisterType().SingleInstance(); - builder.RegisterType().InstancePerLifetimeScope(); - builder.RegisterType().SingleInstance(); - builder.RegisterType(); - builder.RegisterType(); - builder.RegisterType().As(); - builder.Register(context => context.Resolve().CreateReplacement - ? new ReplacementOfSwitchedHandler(context.Resolve()) - : new SwitchedHandler(context.Resolve())) - .As(); - builder.RegisterType() - .OnActivating(e => e.ReplaceInstance(new ReplacementOfActivatedHandler(e.Context.Resolve()))); - builder.RegisterType(); - builder.RegisterType(); - builder.RegisterType(); - builder.RegisterType(); - builder.RegisterType(); - builder.RegisterType(); - builder.RegisterType(); - builder.RegisterType(); - builder.RegisterType(); - - services.OnRegistered(context => - { - if (context.ImplementationType == typeof(InterceptedHandler)) - { - context.Interceptors.TryAdd(); - } - }); - } - - [Fact] - public async Task An_Ioc_Handler_Should_Be_Created_Once_Per_Publish() - { - var tracker = GetRequiredService(); - using (Subscribe()) - { - 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(); - using (Subscribe()) - using (Subscribe()) - { - 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(); - using (Subscribe()) - using (Subscribe()) - { - 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(); - using (Subscribe()) - using (Subscribe()) - { - // 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(); - using (Subscribe()) - using (Subscribe()) - { - 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(); - using (Subscribe()) - using (Subscribe()) - { - 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(); - using (Subscribe()) - using (Subscribe()) - { - (await Should.ThrowAsync(() => 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(); - using (Subscribe()) - using (Subscribe()) - using (Subscribe()) - { - (await Should.ThrowAsync(() => 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(); - var eventName = "RegisteredTypeDynamic-" + Guid.NewGuid().ToString("N"); - using (LocalEventBus.Subscribe(eventName, CreateFactory())) - { - 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(); - using (LocalEventBus.Subscribe(typeof(NamedEventData), CreateFactory())) - using (LocalEventBus.Subscribe(NamedEventData.Name, CreateFactory())) - { - // The typed handler's data cannot be converted, which ends the publish after the dynamic handler ran. - await Should.ThrowAsync(() => ((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(); - using (Subscribe()) - using (Subscribe()) - { - 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(); - var derived = ActivatorUtilities.CreateInstance(ServiceProvider); - using (derived.Subscribe(typeof(RegisteredTypeEventData), CreateFactory())) - using (derived.Subscribe(typeof(RegisteredTypeEventData), CreateFactory())) - { - 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() - { - return LocalEventBus.Subscribe(typeof(TEvent), CreateFactory()); - } - - private IocEventHandlerFactory CreateFactory() - { - return new IocEventHandlerFactory(GetRequiredService(), 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 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 - { - 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 - { - public ConstructionFailingHandler(TrackedDependency dependency) - { - throw new InvalidOperationException("Construction failed."); - } - - public Task HandleEventAsync(RegisteredTypeEventData eventData) - { - return Task.CompletedTask; - } - } - - public class DynamicHandler : ILocalEventHandler - { - 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 - { - 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 - { - 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 - { - 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 - { - 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, 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 options, - IServiceScopeFactory serviceScopeFactory, - ICurrentTenant currentTenant, - IUnitOfWorkManager unitOfWorkManager, - IEventHandlerInvoker eventHandlerInvoker) - : base(options, serviceScopeFactory, currentTenant, unitOfWorkManager, eventHandlerInvoker) - { - } - } -}