Files
Umbraco-CMS/src/Umbraco.Core/Composing/ComponentCollection.cs

66 lines
2.6 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2019-01-03 21:00:28 +01:00
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.Logging;
using Umbraco.Extensions;
2019-01-03 21:00:28 +01:00
namespace Umbraco.Cms.Core.Composing
2019-01-03 21:00:28 +01:00
{
/// <summary>
/// Represents the collection of <see cref="IComponent"/> implementations.
/// </summary>
public class ComponentCollection : BuilderCollectionBase<IComponent>
{
private const int LogThresholdMilliseconds = 100;
2020-09-15 09:12:29 +02:00
private readonly IProfilingLogger _profilingLogger;
private readonly ILogger<ComponentCollection> _logger;
2019-01-03 21:00:28 +01:00
public ComponentCollection(Func<IEnumerable<IComponent>> items, IProfilingLogger profilingLogger, ILogger<ComponentCollection> logger)
2019-01-03 21:00:28 +01:00
: base(items)
{
2020-09-15 09:12:29 +02:00
_profilingLogger = profilingLogger;
2019-01-03 21:00:28 +01:00
_logger = logger;
}
2019-01-07 09:30:47 +01:00
public void Initialize()
{
2020-09-15 09:12:29 +02:00
using (_profilingLogger.DebugDuration<ComponentCollection>($"Initializing. (log components when >{LogThresholdMilliseconds}ms)", "Initialized."))
2019-01-07 09:30:47 +01:00
{
2019-02-14 10:39:27 +01:00
foreach (var component in this)
2019-01-07 09:30:47 +01:00
{
var componentType = component.GetType();
2020-09-15 09:12:29 +02:00
using (_profilingLogger.DebugDuration<ComponentCollection>($"Initializing {componentType.FullName}.", $"Initialized {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds))
2019-01-07 09:30:47 +01:00
{
component.Initialize();
}
}
}
}
2019-01-03 21:00:28 +01:00
public void Terminate()
{
2020-09-15 09:12:29 +02:00
using (_profilingLogger.DebugDuration<ComponentCollection>($"Terminating. (log components when >{LogThresholdMilliseconds}ms)", "Terminated."))
2019-01-03 21:00:28 +01:00
{
foreach (var component in this.Reverse()) // terminate components in reverse order
{
var componentType = component.GetType();
2020-09-15 09:12:29 +02:00
using (_profilingLogger.DebugDuration<ComponentCollection>($"Terminating {componentType.FullName}.", $"Terminated {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds))
2019-01-03 21:00:28 +01:00
{
try
{
component.Terminate();
component.DisposeIfDisposable();
}
catch (Exception ex)
{
2020-09-15 09:12:29 +02:00
_logger.LogError(ex, "Error while terminating component {ComponentType}.", componentType.FullName);
}
2019-01-03 21:00:28 +01:00
}
}
}
}
}
}