• Avalanche
  • Avalanche.Core
  • Lexical

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IContentAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • Dependency Injection
        • AccessorMessages
    • Avalanche.Binding
      • Introduction
    • Avalanche.Core
      • License
      • Order
    • Avalanche.DataType
      • Introduction
      • DataType
        • IDataType
        • IListType
        • IMapType
        • IRecordType
        • IFieldType
        • IOneOfType
        • IAnyType
        • IStringType
        • IValueType
        • IIntegerType
        • IEnumerationType
        • IRealType
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • Enum
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystem
          • IFileSystemBrowse
          • IFileSystemCreateDirectory
          • IFileSystemDelete
          • IFileSystemFileAttribute
          • IFileSystemMount
          • IFileSystemMove
          • IFileSystemObserve
          • IFileSystemOpen
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Events
      • Utilities
        • Dispose
        • File Scanner
        • Visit Tree
        • File Operation
    • Avalanche.Identity
      • Introduction
      • Identity
      • IdentityParts
      • IdentityInterner
      • IdentityComparer
      • Print Tree
      • IdentityAccessors
        • Introduction
        • TypeName
    • Avalanche.Localization
      • Introduction
      • Localization
      • LocalizationFile
      • LocalizationFiles
      • LocalizationFileSystem
      • LocalizationFileFormat
      • LocalizationLine
      • LocalizationLines
      • TemplateFormat
      • CultureProvider
      • FallbackCultureProvider
      • ResourceManager
      • LocalizationError
      • Microsoft.Extensions
        • Introduction
        • DependencyInjection
        • FileProvider
        • Logging
        • ITextLocalizer
        • IFileLocalizer
        • Localization
        • Asp.Net
        • Asp.Net (Min Api)
      • Pluralization
        • Introduction
        • Multiple plural parameters
        • Custom PluralRules
        • Invariant Culture
        • Unit Prefix
        • IPluralRule
        • IPluralNumber
        • IPluralRules
        • CLDRs
        • Unicode.CLDR41
        • Unicode.CLDR40
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Logging
      • Validation
      • Localization
    • Avalanche.Service
      • Introduction
      • Service
        • Introduction
        • IService
        • IServiceDisposable
        • IServiceDecoration
        • IServiceCast
        • IServiceObservable
        • IServiceContainer
        • Construction
        • Query
        • CancellationToken
        • CachePolicy
        • Scope
      • Handler
        • Introduction
        • IHandler
        • IHandlerCast
        • IHandlerDecoration
        • IHandlerWithOrder
        • CancellationToken
        • Cyclicity
        • Delegates
        • Invokable
        • ExportAttribute
        • OrderAttribute
        • PrintTree
        • Recursion
      • Query
        • Introduction
        • IQuery
        • IQueryCast
        • IQueryDecoration
      • Entry
        • Introduction
        • IEntry
        • IEntryCast
        • IEntryDecoration
        • IEntryObservable
        • IEntryVisitable
        • EntryState
      • Request
        • Introduction
        • IRequest
        • IRequestFor
        • IRequestToBeCached
        • IRequestToBeDisposed
        • RequestAttribute
        • ContextParameterAttribute
        • Print Tree
      • Dependency Injection
        • Introduction
        • Asp.Net
        • ServiceRequest<T>
        • Decorating a service
        • Handler
        • CachePolicy
        • CancellationToken
        • QueryLogger
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • ItfMessages
        • Win32Messages
        • ClrMessages
      • System
        • Introduction
        • AccessControlMessages
        • AggregateMessages
        • AppDomainMessages
        • ArgumentMessages
        • ArgumentNullMessages
        • ArgumentOutOfRangeMessages
        • ArithmeticMessages
        • ArrayMessages
        • AssemblyMessages
        • BadImageFormatMessages
        • CodeContractMessages
        • CodePageMessages
        • CollectionsMessages
        • CompilerServiceMessages
        • CryptographyMessages
        • CultureMessages
        • DiagnosticsMessages
        • EventSourceMessages
        • ExecutionEngineMessages
        • FormatMessages
        • HostProtectionMessages
        • IOMessages
        • IndexOutOfRangeMessages
        • InteropServiceMessages
        • InvalidCastMessages
        • InvalidOperationMessages
        • IsolatedStorageMessages
        • LazyMessages
        • MarshalerMessages
        • MemoryMessages
        • MiscellaneousMessages
        • NotImplementedMessages
        • NotSupportedMessages
        • ObjectDisposedMessages
        • OperationCanceledMessages
        • OverflowMessages
        • PlatformMessages
        • PolicyMessages
        • PrincipalMessages
        • ProgramMessages
        • ReferenceMessages
        • ReflectionMessages
        • RegionMessages
        • RemotingMessages
        • ResourcesMessages
        • SecurityMessages
        • SerializationMessages
        • StackMessages
        • TaskMessages
        • TextMessages
        • ThreadingMessages
        • TimeZoneMessages
        • TypeMessages
        • XmlMessages
    • Avalanche.Template
      • Introduction
      • TemplateFormats
      • ITemplatePrintable
      • ITemplateFormatPrintable
      • ITemplateText
      • ITemplateBreakdown
      • ITemplateFormat
      • ITemplateFormats
      • Extract Arguments
      • Emplacement
    • Avalanche.Tokenizer
      • Introduction
      • IToken
      • ITokenizer
      • Tokenizers
    • Avalanche.Utilities
      • Introduction
      • Collections
        • Tuples
        • StructList
        • ArrayList
        • BijectionMap
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • EnumerableExtensions
        • TupleUtilities
        • ArrayUtilities
      • Comparers
        • IGraphComparer
        • IGraphComparable
        • AlphaNumericComparer
        • EnumerableComparer
        • EnumerableGraphComparer
        • ReferenceComparer
        • KeyValuePairComparer
        • DefaultComparerProvider
        • RecordComparer
      • Cloners
        • ICloner
        • IGraphCloner
        • IGraphCloneable
        • ListCloner
        • DictionaryCloner
        • FieldCloner
        • PassthroughCloner
        • RecordCloner
        • ClonerProvider
      • Dispose
        • IDisposeAttachable
        • IDisposeBelatable
      • Provider
        • Introduction
        • ProviderBase
        • Delegate
        • Pipe
        • Cache
        • ResultCapture
        • AsReadOnly
        • AsService
        • IProviderEvent
      • Record
        • IRecordDescription
        • IFieldDescription
        • IConstructorDescription
        • IConstructionDescription
        • IParameterDescription
        • IRecordProviders
        • RecordDelegates
          • RecordCreate
          • RecordClone
          • RecordCopy
          • IRecordDelegates
        • FieldDelegates
          • FieldRead
          • FieldWrite
          • RecreateWith
          • IFieldDelegates
      • String
        • IEscaper
        • UnicodeString
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    Decorating a service

    When using Avalanche.Service as dependency injection, any handler can participate in the build process of ServiceDescriptors by exposing method Handle<R, T>(IQuery<R, IServiceList<ServiceType>> query) where R : IServiceProducerRequest<ServiceType>.

    /// <summary>Handler that decorates loggers.</summary>
    public class LoggerDecorator : IHandlerBase
    {
        /// <summary>Decorate loggers in every producer request</summary>
        [Order(9_000_000_000_000_000_000L)] // Participation order
        public void Handle<R, T>(IQuery<R, IServiceList<ILogger<T>>> query) where R : IServiceProducerRequest<ILogger<T>>
        {
            // No loggers
            if (query.Response.Value() is not IServiceList<ILogger<T>> list || list.Count == 0) return;
            // Decorate each logger
            for (int i = 0; i < list.Count; i++)
            {
                // Get logger
                ILogger<T> logger = list.Elements[i];
                // Decorate logger
                ILogger<T> loggerDecoration = new LoggerDecoration<T>(logger);
                // Assign decoration
                list.Elements[i] = loggerDecoration;
            }
        }
    }
    
    /// <summary><see cref="ILogger"/> that is decorated.</summary>
    public class LoggerDecoration<T> : ILogger<T>
    {
        /// <summary></summary>
        ILogger<T> source;
        /// <summary></summary>
        public LoggerDecoration(ILogger<T> source)
        {
            this.source = source;
        }
        /// <summary></summary>
        public IDisposable BeginScope<TState>(TState state) => source.BeginScope<TState>(state);
        /// <summary></summary>
        public bool IsEnabled(LogLevel logLevel) => source.IsEnabled(logLevel);
        /// <summary></summary>
        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            // Print
            string print = formatter(state, exception);
            // Debug print
            Console.WriteLine($"LoggerDecoration Here: {print}");
            // Call source logger
            source.Log<TState>(logLevel, eventId, state, exception, formatter);
        }
    }
    

    The following example uses modified ILogger<T> instances.

    // Create service collection
    IServiceCollection serviceCollection = new ServiceCollection()
        .AddLogging()
        .AddHandler(new LoggerDecorator())
        .AddHandlers(ServiceHandlers.Instance)
        .AddTransient<MyRecord>();
    // Create service
    using var service = serviceCollection.BuildAvalancheServiceProvider(cachePolicy: CachePolicies.Default);
    // Get myclass
    MyRecord myClass = service.GetRequiredService<MyRecord>();
    // Log with decorated logger
    myClass.Logger.LogInformation("Hello world");
    // "LoggerDecoration Here: Hello world"
    
    /// <summary>Dependency injectible class</summary>
    public record MyRecord(ILogger<MyRecord> Logger);
    

    Same example on Asp.Net.

    WebApplicationBuilder builder = WebApplication.CreateBuilder();
    builder.Host.UseServiceProviderFactory(Avalanche.Service.ServiceProviderFactory.Instance);
    builder.Host.ConfigureContainer((HostBuilderContext _, IServiceBuilder sb) =>
    {
        // Add handlers
        sb.AddHandler(new LoggerDecorator());
    });
    WebApplication app = builder.Build();
    app.MapGet("/", ([FromServices] Avalanche.Service.IService service) => Results.Ok("Hello world"));
    // LoggerDecoration Here: Executing endpoint 'HTTP: GET /'
    // LoggerDecoration Here: Executed endpoint 'HTTP: GET /'
    

    Full Example

    Full example
    using System;
    using System.Threading.Tasks;
    using Avalanche.Service;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    using static System.Console;
    
    public class di_loggerdecorator
    {
        public static void Run()
        {
            {
                // <11>
                // Create service collection
                IServiceCollection serviceCollection = new ServiceCollection()
                    .AddLogging()
                    .AddHandler(new LoggerDecorator())
                    .AddHandlers(ServiceHandlers.Instance)
                    .AddTransient<MyRecord>();
                // Create service
                using var service = serviceCollection.BuildAvalancheServiceProvider(cachePolicy: CachePolicies.Default);
                // Get myclass
                MyRecord myClass = service.GetRequiredService<MyRecord>();
                // Log with decorated logger
                myClass.Logger.LogInformation("Hello world");
                // "LoggerDecoration Here: Hello world"
                // </11>
                WriteLine(myClass.Logger.GetType());
                WriteLine(service);
            }
            {
                // <21>
                WebApplicationBuilder builder = WebApplication.CreateBuilder();
                builder.Host.UseServiceProviderFactory(Avalanche.Service.ServiceProviderFactory.Instance);
                builder.Host.ConfigureContainer((HostBuilderContext _, IServiceBuilder sb) =>
                {
                    // Add handlers
                    sb.AddHandler(new LoggerDecorator());
                });
                WebApplication app = builder.Build();
                app.MapGet("/", ([FromServices] Avalanche.Service.IService service) => Results.Ok("Hello world"));
                // LoggerDecoration Here: Executing endpoint 'HTTP: GET /'
                // LoggerDecoration Here: Executed endpoint 'HTTP: GET /'
                // </21>
    
                // Shutdown in 5 seconds ...
                Task.Run(async () =>
                {
                    await Task.Delay(5000);
                    app.Services.GetService<IHostApplicationLifetime>()!.StopApplication();
                });
    
                app.Run();
            }
        }
    
        // <99>
        /// <summary>Handler that decorates loggers.</summary>
        public class LoggerDecorator : IHandlerBase
        {
            /// <summary>Decorate loggers in every producer request</summary>
            [Order(9_000_000_000_000_000_000L)] // Participation order
            public void Handle<R, T>(IQuery<R, IServiceList<ILogger<T>>> query) where R : IServiceProducerRequest<ILogger<T>>
            {
                // No loggers
                if (query.Response.Value() is not IServiceList<ILogger<T>> list || list.Count == 0) return;
                // Decorate each logger
                for (int i = 0; i < list.Count; i++)
                {
                    // Get logger
                    ILogger<T> logger = list.Elements[i];
                    // Decorate logger
                    ILogger<T> loggerDecoration = new LoggerDecoration<T>(logger);
                    // Assign decoration
                    list.Elements[i] = loggerDecoration;
                }
            }
        }
    
        /// <summary><see cref="ILogger"/> that is decorated.</summary>
        public class LoggerDecoration<T> : ILogger<T>
        {
            /// <summary></summary>
            ILogger<T> source;
            /// <summary></summary>
            public LoggerDecoration(ILogger<T> source)
            {
                this.source = source;
            }
            /// <summary></summary>
            public IDisposable BeginScope<TState>(TState state) => source.BeginScope<TState>(state);
            /// <summary></summary>
            public bool IsEnabled(LogLevel logLevel) => source.IsEnabled(logLevel);
            /// <summary></summary>
            public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
            {
                // Print
                string print = formatter(state, exception);
                // Debug print
                Console.WriteLine($"LoggerDecoration Here: {print}");
                // Call source logger
                source.Log<TState>(logLevel, eventId, state, exception, formatter);
            }
        }
        // </99>
    
        // <19>
        /// <summary>Dependency injectible class</summary>
        public record MyRecord(ILogger<MyRecord> Logger);
        // </19>
    }
    
    Back to top Copyright © 2022 Toni Kalajainen, contact@avalanche.fi