Register as singleton, test DI into handlers.

This commit is contained in:
James Jackson-South
2020-12-01 12:09:50 +00:00
parent a3cc3769c0
commit ea79051104
2 changed files with 19 additions and 11 deletions

View File

@@ -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<ServiceFactory>(p => p.GetService);
Services.TryAdd(new ServiceDescriptor(typeof(IEventAggregator), typeof(EventAggregator), ServiceLifetime.Transient));
// Register as singleton to allow injection everywhere.
Services.AddSingleton<ServiceFactory>(p => p.GetService);
Services.AddSingleton<IEventAggregator, EventAggregator>();
}
}
}

View File

@@ -28,6 +28,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Events
[Test]
public async Task CanPublishEvents()
{
_builder.Services.AddScoped<Adder>();
_builder.AddNotificationHandler<Notification, NotificationHandlerA>();
_builder.AddNotificationHandler<Notification, NotificationHandlerB>();
_builder.AddNotificationHandler<Notification, NotificationHandlerC>();
@@ -65,11 +66,23 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Events
public class NotificationHandlerC : INotificationHandler<Notification>
{
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;
}
}
}
}