diff --git a/src/Umbraco.Core/Builder/UmbracoBuilder.cs b/src/Umbraco.Core/Builder/UmbracoBuilder.cs index b167f1694f..2a5c93b0d7 100644 --- a/src/Umbraco.Core/Builder/UmbracoBuilder.cs +++ b/src/Umbraco.Core/Builder/UmbracoBuilder.cs @@ -1,13 +1,12 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; +using System; +using System.Collections.Generic; using Umbraco.Core.Builder; using Umbraco.Core.Composing; using Umbraco.Core.Events; -using Microsoft.Extensions.DependencyInjection.Extensions; namespace Umbraco.Web.Common.Builder { @@ -62,13 +61,9 @@ namespace Umbraco.Web.Common.Builder private void AddCoreServices() { - // TODO: Should this be an explicit public method accepting a service lifetime? - // Register the aggregator and factory as transient. - // Use TryAdd to allow simple refactoring to allow additional registrations. - // Transiant registration matches the default registration of Mediatr and - // should encourage the avoidance of singletons throughout the codebase. - Services.TryAddTransient(p => p.GetService); - Services.TryAdd(new ServiceDescriptor(typeof(IEventAggregator), typeof(EventAggregator), ServiceLifetime.Transient)); + // Register as singleton to allow injection everywhere. + Services.AddSingleton(p => p.GetService); + Services.AddSingleton(); } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Events/EventAggregatorTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Events/EventAggregatorTests.cs index c89fa2f9fd..9c1fd87974 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Events/EventAggregatorTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Events/EventAggregatorTests.cs @@ -28,6 +28,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Events [Test] public async Task CanPublishEvents() { + _builder.Services.AddScoped(); _builder.AddNotificationHandler(); _builder.AddNotificationHandler(); _builder.AddNotificationHandler(); @@ -65,11 +66,23 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Events public class NotificationHandlerC : INotificationHandler { + private readonly Adder _adder; + + public NotificationHandlerC(Adder adder) => _adder = adder; + public Task HandleAsync(Notification notification, CancellationToken cancellationToken) { - notification.SubscriberCount += C; + notification.SubscriberCount = _adder.Add(notification.SubscriberCount, C); return Task.CompletedTask; } } + + public class Adder + { + public int Add(int a, int b) + { + return a + b; + } + } } }