Created
October 3, 2017 17:58
-
-
Save onyxmaster/519b5318719a3801eb00b5b035df93cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Reflection; | |
using Dnet.Reflection; | |
using SimpleInjector; | |
using SimpleInjector.Diagnostics; | |
namespace Dnet.Composition.Composition | |
{ | |
/// <summary> | |
/// Composes container verification. | |
/// </summary> | |
/// | |
/// <threadsafety instance="true" static="true">See <see cref="ICompositionPackage"/>.</threadsafety> | |
public sealed class VerificationPackage : CompositionPackageBase | |
{ | |
// THREADSAFE: immutable reference, immutable value | |
private static readonly InstanceMethodCaller<Registration, DiagnosticType, bool> RegistrationShouldNotBeSuppressed = | |
new InstanceMethodCaller<Registration, DiagnosticType, bool>("ShouldNotBeSuppressed", true); | |
/// <inheritdoc/> | |
public override int InitializationOrder => -10000; | |
/// <inheritdoc/> | |
public override void InitializeApplication(Container container) | |
{ | |
container.Expect(nameof(container)); | |
container.Verify(VerificationOption.VerifyAndDiagnose); | |
var containerResults = Analyzer.Analyze(container); | |
var lifestyleResults = AnalyzeLifestyle(container); | |
if (containerResults.Length == 0 && lifestyleResults.Count == 0) | |
{ | |
return; | |
} | |
var results = new List<DiagnosticResult>(); | |
results.AddRangeHinted(containerResults); | |
results.AddRangeHinted(lifestyleResults); | |
throw new DiagnosticVerificationException(results); | |
} | |
private static IReadOnlyCollection<DiagnosticResult> AnalyzeLifestyle(Container container) | |
{ | |
container.Expect(nameof(container)); | |
var results = new List<DiagnosticResult>(); | |
foreach (var producer in container.GetRootRegistrations()) | |
{ | |
var lifestyle = producer.Lifestyle; | |
if (lifestyle != Lifestyle.Transient) | |
{ | |
continue; | |
} | |
var registration = producer.Registration; | |
if (!RegistrationShouldNotBeSuppressed[registration, DiagnosticType.DisposableTransientComponent]) | |
{ | |
continue; | |
} | |
var description = Safe.Fmt($"Transient lifestyle detected for {producer.ServiceType} implemented by {registration.ImplementationType}."); | |
var args = new object[] { producer.ServiceType, producer, description }; | |
var diagnosticResult = (DiagnosticResult)Activator.CreateInstance(typeof(DisposableTransientComponentDiagnosticResult), BindingFlags.Instance | BindingFlags.NonPublic, null, args, null); | |
results.Add(diagnosticResult); | |
} | |
return results; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment