• Avalanche.Core
Search Results for

    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.Configuration
      • Introduction
      • Configuration Binding
      • ConfigurationExtensions
      • MemoryConfiguration
      • PrintTree
      • Saving IOptions
      • Yaml
    • Avalanche.Converter
      • Introduction
      • EnumConverter
      • Func<,>
      • HexConverter
      • PrimitiveConverter
      • StringConverter
    • Avalanche.Core
      • License
    • 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
        • FilterEnumerable
        • PollingFilterWatchToken
    • 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
        • Introduction
        • Supplying localization
        • Inject to pages
        • Culture Assigned
        • Minimalistic Api
        • Diagnostics
      • Pluralization
        • Introduction
        • Multiple plural parameters
        • Custom PluralRules
        • Invariant Culture
        • Unit Prefix
        • IPluralRule
        • IPluralNumber
        • IPluralRules
        • CLDRs
        • Unicode.CLDR40
        • Unicode.CLDR41
        • Unicode.CLDR42
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Logging
        • Validation
    • Avalanche.Options
      • Introduction
      • OptionsExtensions
      • OptionsMonitorCast
    • 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
        • IHostBuilder
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • StorageMessages
        • ItfMessages
        • Win32Messages
        • WindowsMessages
        • SspiMessages
        • CertMessages
        • MediaServerMessages
        • SetupApiMessages
        • ScardMessages
        • ComPlusMessages
        • ClrMessages
        • UserModeFilterManagerMessages
        • GraphicsMessages
        • TpmServicesMessages
        • TpmSoftwareMessages
        • PlaMessages
        • FveMessages
        • FwpMessages
        • NdisMessages
        • DltMessages
      • 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
      • HttpStatusCode
      • OpcUaStatusCode
    • 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
      • Reflection
        • EnumDescription
      • String
        • IEscaper
        • UnicodeString
        • Hex
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • ITreeNode
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    IHandlerDecoration

    IHandlerDecoration indicates that handler is a decoration of another handler.

    /// <summary>Indicates that handler is based on decorating another <see cref="IHandlerBase"/>.</summary>
    public interface IHandlerDecoration : IHandlerBase
    {
        /// <summary>Is decoration</summary>
        bool IsHandlerDecoration { get; }
        /// <summary>The underlying <see cref="IHandlerBase"/> this decoration is derivation of.</summary>
        IHandlerBase? DecorationSource { get; }
    }
    

    IHandlerDecorator decorates a handler in some specific way.

    /// <summary>Decorates <see cref="IHandlerBase"/> in an specific way.</summary>
    public interface IHandlerDecorator
    {
        /// <summary>Decorate <paramref name="handler"/></summary>
        /// <param name="handler"></param>
        /// <returns>Decorated version of <paramref name="handler"/>. May or may not implement <see cref="IHandlerDecoration"/>.</returns>
        IHandlerBase Decorate(IHandlerBase handler);
    }
    

    Decorator applies a decoration to a handler.

    // Create sum calculator
    Action<IQuery<(int, int), int>> sumCalculator = q => q.Response.SetValue(q.Request.Item1 + q.Request.Item2);
    // Cast to handler
    IHandlerBase handler = Handlers.Action(sumCalculator);
    // Create decorator
    IHandlerDecorator decorator = new LoggingDecorator(Console.Out);
    // Decorate handler to log 
    handler = decorator.Decorate(handler);
    // Create service
    IService<(int, int), int> service = Services.CreateWithoutCache<(int, int), int>(handler);
    // Query (logs with decorator)
    int value = service.GetRequired((10, 20));
    // The decoration prints: "(10, 20) = Entry<Object>(Value, 30, , Default)"
    
    public class LoggingDecorator : IHandlerDecorator
    {
        static ConstructorT2<IHandlerBase, TextWriter, IHandlerBase> ctor = new(typeof(LoggingDecoration<,>));
        TextWriter writer;
        public LoggingDecorator(TextWriter writer) => this.writer = writer;
    
        public IHandlerBase Decorate(IHandlerBase handler)
        {
            if (TypeUtilities.TryGetTypeArgumentOfCorrespondingDefinedType(handler.GetType(), typeof(IHandler<,>), 0, out Type requestType) &&
                TypeUtilities.TryGetTypeArgumentOfCorrespondingDefinedType(handler.GetType(), typeof(IHandler<,>), 1, out Type responseType))
            {
                IHandlerBase decoration = ctor.Create(requestType, responseType, handler, writer);
                return decoration;
            }
            else throw new NotSupportedException($"{handler.GetType()} is not supported.");
        }
    }
    
    public class LoggingDecoration<Request, Response> : IHandler<Request, Response>, IHandlerDecoration where Request : notnull
    {
        public bool IsHandlerDecoration => true;
        public IHandlerBase? DecorationSource => source;
    
        IHandler<Request, Response> source;
        TextWriter writer;
    
        public LoggingDecoration(IHandlerBase source, TextWriter writer)
        {
            this.source = (IHandler<Request, Response>)source;
            this.writer = writer;
        }
    
        public void Handle(IQuery<Request, Response> query)
        {
            try
            {
                source.Handle(query);
            } finally
            {
                writer.WriteLine($"{query.Request} = {query.Response}");
            }
        }
    }
    

    Full Example

    Full example
    using System;
    using System.IO;
    using Avalanche.Service;
    using Avalanche.Utilities;
    
    public class handler_decoration
    {
        public static void Run()
        {
            {
                // <01>
                // Create sum calculator
                Action<IQuery<(int, int), int>> sumCalculator = q => q.Response.SetValue(q.Request.Item1 + q.Request.Item2);
                // Cast to handler
                IHandlerBase handler = Handlers.Action(sumCalculator);
                // Create decorator
                IHandlerDecorator decorator = new LoggingDecorator(Console.Out);
                // Decorate handler to log 
                handler = decorator.Decorate(handler);
                // Create service
                IService<(int, int), int> service = Services.CreateWithoutCache<(int, int), int>(handler);
                // Query (logs with decorator)
                int value = service.GetRequired((10, 20));
                // The decoration prints: "(10, 20) = Entry<Object>(Value, 30, , Default)"
                // </01>
            }
        }
    
        // <98>
        public class LoggingDecorator : IHandlerDecorator
        {
            static ConstructorT2<IHandlerBase, TextWriter, IHandlerBase> ctor = new(typeof(LoggingDecoration<,>));
            TextWriter writer;
            public LoggingDecorator(TextWriter writer) => this.writer = writer;
    
            public IHandlerBase Decorate(IHandlerBase handler)
            {
                if (TypeUtilities.TryGetTypeArgumentOfCorrespondingDefinedType(handler.GetType(), typeof(IHandler<,>), 0, out Type requestType) &&
                    TypeUtilities.TryGetTypeArgumentOfCorrespondingDefinedType(handler.GetType(), typeof(IHandler<,>), 1, out Type responseType))
                {
                    IHandlerBase decoration = ctor.Create(requestType, responseType, handler, writer);
                    return decoration;
                }
                else throw new NotSupportedException($"{handler.GetType()} is not supported.");
            }
        }
        // </98>
    
        // <99>
        public class LoggingDecoration<Request, Response> : IHandler<Request, Response>, IHandlerDecoration where Request : notnull
        {
            public bool IsHandlerDecoration => true;
            public IHandlerBase? DecorationSource => source;
    
            IHandler<Request, Response> source;
            TextWriter writer;
    
            public LoggingDecoration(IHandlerBase source, TextWriter writer)
            {
                this.source = (IHandler<Request, Response>)source;
                this.writer = writer;
            }
    
            public void Handle(IQuery<Request, Response> query)
            {
                try
                {
                    source.Handle(query);
                } finally
                {
                    writer.WriteLine($"{query.Request} = {query.Response}");
                }
            }
        }
        // </99>
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen