• 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

    ServiceRequest<T>

    When ServiceDescription is adapted to handler, the service requests placed on IServiceProvider are forwarded to IService as ServiceRequest<T>. All handlers can participate in the build process of requested services. Handlers can initialize, modify and decorate the result.

    IServiceProvider.GetService(Type) requests are forwarded as ServiceRequest<T> requests.

    MyClass instance = (MyClass)service.GetService(typeof(MyClass))!;
    

    ServiceRequest<T> are received and processed by ServiceRequestHandler (included in ServiceHandlers). ServiceRequest<T> is the request on the consumer side.

    MyClass instance = service.GetRequired<ServiceRequest<MyClass>, MyClass>(default);
    

    ServiceRequestT.Create(type) constructs a ServiceRequest<T> for a specific run-time type.

    // Create request
    IServiceRequest request = ServiceRequestT.CreateCached(typeof(MyClass));
    // Get service
    MyClass instance = service.GetRequired<IServiceRequest, MyClass>(request);
    

    IServiceProducerRequest<T>

    IServiceProducerRequest<T> is the interface for the three producer side requests.

    IServiceProducerRequest<T>
    ├── SingletonServiceRequest<T>
    ├── ScopedServiceRequest<T>
    └── TransientServiceRequest<T>
    

    ServiceRequestHandler forwards ServiceRequest<T> as three sub-requests: SingletonServiceRequest<T>, ScopedServiceRequest<T> and TransientServiceRequest<T>.

    Service DI

    Handler serves one of these request types and appends value in IServiceList<T>. The selected request type affects the dispose and cache policy of the result.

    /// <summary>Creates lists with huge initial capacity.</summary>
    public class LargeListBuilder : IHandlerBase
    {
        /// <summary>Constructs <![CDATA[List<>]]> instances</summary>
        ConstructorT<int, IList> listConstructor = new(typeof(List<>));
    
        /// <summary>Serve <![CDATA[ServiceRequest<List<>>]]></summary>
        public void Handle<T>(IQuery<TransientServiceRequest<List<T>>, IServiceList<List<T>>> query)
        {
            // Unexpected status
            if (query.Response.Status.ExcludeFlags() > EntryStatus.Value) return;
            // Get response container
            IServiceList<List<T>>? response = query.Response.Value<IServiceList<List<T>>>() ?? query.Response.PassValue<IServiceList<List<T>>>(new ServiceList<List<T>>());
    
            // Create List<T> with Capacity = 1_000_000
            IList largeList = listConstructor.Create(typeof(T), 1_000_000);
            // Append to result
            response.Add(largeList, new IServiceList.Line(Order: 0L, ToDispose: false));
        }
    }
    
    // Create service collection
    IServiceCollection serviceCollection = new ServiceCollection()
        .AddHandler(new LargeListBuilder())
        .AddHandlers(ServiceHandlers.Instance.ServiceRequestHandler)
        .AddCachePolicy(CachePolicies.Default);
    // Create service
    using var service = serviceCollection.BuildAvalancheServiceProvider();
    // Create list with Capacity = 1_000_000
    List<int> instance = service.GetRequiredService<List<int>>();
    

    Handlers participate in service query by modifiying IServiceList<T>.

    /// <summary>Participate in <![CDATA[IEnumerable<string>]]> service request</summary>
    public class StringsService : IHandlerBase
    {
        /// <summary></summary>
        [Order(1000)] // After ServiceDescriptor (0)
        public void Handle(IQuery<SingletonServiceRequest<string>, IServiceList<string>> query)
        {
            // Unexpected status
            if (query.Response.Status.ExcludeFlags() > EntryStatus.Value) return;
            // Get response container
            IServiceList<string>? list = query.Response.Value<IServiceList<string>>() ?? query.Response.PassValue<IServiceList<string>>(new ServiceList<string>());
    
            // String to add to service enumeration
            string str = "Participated in service request (first line)";
            // Append as first result value (Order = long.MinValue)
            list.Add(str, new IServiceList.Line(Order: long.MinValue, ToDispose: false));
    
            // String to add to service enumeration
            str = "Participated in service request (last line)";
            // Append as last result value (Order = long.MaxValue)
            list.Add(str, new IServiceList.Line(Order: long.MaxValue, ToDispose: false));
        }
    }
    
    // Create service collection
    IServiceCollection serviceCollection = new ServiceCollection()
        .AddHandlers(ServiceHandlers.Instance.ServiceRequestHandler)
        .AddSingleton<string>("Hello")
        .AddSingleton<string>("World")
        .AddHandler(new StringsService());
    // Create service provider
    using var service = serviceCollection.BuildAvalancheServiceProvider();
    // Request service IEnumerable<string>
    IEnumerable<string> strings = service.GetRequiredService<IEnumerable<string>>();
    // Print four strings
    foreach (var str in strings) Console.WriteLine(str);
    // "Participated in service request (first line)"
    // "Hello"
    // "World"
    // "Participated in service request(last line)"
    
    IServiceList<T>
    /// <summary>
    /// List that has elements and associated sort order. 
    /// 
    /// Elements and order values are in separate sub-lists, so that a reference to element and order lists can be taken distictively. 
    /// 
    /// List not maintained in sorted order, but must be put into order with explicit <see cref="Sort"/> call.
    /// 
    /// List has mutability state, and throws <see cref="InvalidOperationException"/> if is modified after put into read-only state.
    /// </summary>
    public interface IServiceList : IReadOnly, IDisposable
    {
        /// <summary>Get element type</summary>
        Type ElementType { get; }
        /// <summary>Get element at index.</summary>
        object this[int index] { get; }
        /// <summary>Elements as <![CDATA[IList<T>]]></summary>
        object Elements { get; set; }
        /// <summary>Orders, each line corresponds to line in <see cref="Elements"/></summary>
        IList<Line> Lines { get; set; }
        /// <summary>Get number of lines</summary>
        int Count { get; }
        /// <summary>Sort <see cref="Elements"/> by <see cref="Lines"/> values in ascending order. Must be in mutable-state.</summary>
        void Sort();
        /// <summary>Sort <see cref="Elements"/> by <see cref="Lines"/> values in decending order. Must be in mutable-state.</summary>
        void InverseSort();
        /// <summary>Add <paramref name="element"/> with associated order value <paramref name="order"/>.</summary>
        void Add(object element, Line line);
        /// <summary>object that can be used to synchronize the access.</summary>
        object SyncRoot { get; }
        /// <summary>Create T[]</summary>
        Array ToArray();
        /// <summary>Add all elements and lines from <paramref name="listFrom"/>.</summary>
        void AddAll(IServiceList listFrom);
    
        /// <summary>Service meta info</summary>
        public record struct Line(long Order, bool ToDispose);
    }
    
    /// <summary>
    /// List that has elements and associated sort order. 
    /// 
    /// Elements and order values are in separate sub-lists, so that a reference to element and order lists can be taken distictively. 
    /// 
    /// List is not maintained in sorted order, but must be put into order with explicit <see cref="IServiceList.Sort"/> call.
    /// 
    /// List has mutability state, and throws <see cref="InvalidOperationException"/> if is modified after put into read-only state.
    /// </summary>
    public interface IServiceList<T> : IServiceList
    {
        /// <summary></summary>
        new IList<T> Elements { get; set; }
        /// <summary>Add <paramref name="element"/> with associated order value <paramref name="order"/>.</summary>
        void Add(T element, Line line);
    }
    

    See logger decorator example.

    Full Example

    Full example
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using Avalanche.Service;
    using Avalanche.Utilities;
    using Microsoft.Extensions.DependencyInjection;
    using static System.Console;
    
    public class di_servicerequest
    {
        public static void Run()
        {
            {
                // Create service collection
                IServiceCollection serviceCollection = new ServiceCollection()
                    .AddHandlers(ServiceHandlers.Instance.ServiceRequestHandler)
                    .AddCachePolicy(CachePolicies.Default)
                    .AddTransient<MyClass>();
                // Create service
                using IServiceDisposable service = serviceCollection.BuildAvalancheServiceProvider();
                // Get instance
                // <01>
                MyClass instance = service.GetRequired<ServiceRequest<MyClass>, MyClass>(default);
                // </01>
                WriteLine(instance);
            }
            {
                // Create service collection
                IServiceCollection serviceCollection = new ServiceCollection()
                    .AddHandlers(ServiceHandlers.Instance.ServiceRequestHandler)
                    .AddCachePolicy(CachePolicies.Default)
                    .AddTransient<MyClass>();
                // Create service
                using IServiceDisposable service = serviceCollection.BuildAvalancheServiceProvider();
                // <02>
                // Create request
                IServiceRequest request = ServiceRequestT.CreateCached(typeof(MyClass));
                // Get service
                MyClass instance = service.GetRequired<IServiceRequest, MyClass>(request);
                // </02>
                WriteLine(instance);
            }
            {
                // Create service collection
                IServiceCollection serviceCollection = new ServiceCollection()
                    .AddHandlers(ServiceHandlers.Instance.ServiceRequestHandler)
                    .AddCachePolicy(CachePolicies.Default)
                    .AddTransient<MyClass>();
                // Create service
                using IServiceDisposable service = serviceCollection.BuildAvalancheServiceProvider();
                // Get instance
                // <03>
                MyClass instance = (MyClass)service.GetService(typeof(MyClass))!;
                // </03>
                WriteLine(instance);
            }
            {
                // Create service collection
                IServiceCollection serviceCollection = new ServiceCollection()
                    .AddHandlers(ServiceHandlers.Instance.ServiceRequestHandler)
                    .AddCachePolicy(CachePolicies.Default)
                    .AddTransient<MyClass>();
                // Create service
                using IServiceDisposable service = serviceCollection.BuildAvalancheServiceProvider();
                // <04>
                // Create request
                IServiceRequest request = ServiceRequestT.CreateCached(typeof(MyClass));
                // Get instance
                MyClass instance = service.GetRequired<IServiceRequest, MyClass>(request);
                // </04>
                WriteLine(instance);
            }
    
            {
                // <31>
                // Create service collection
                IServiceCollection serviceCollection = new ServiceCollection()
                    .AddHandler(new LargeListBuilder())
                    .AddHandlers(ServiceHandlers.Instance.ServiceRequestHandler)
                    .AddCachePolicy(CachePolicies.Default);
                // Create service
                using var service = serviceCollection.BuildAvalancheServiceProvider();
                // Create list with Capacity = 1_000_000
                List<int> instance = service.GetRequiredService<List<int>>();
                // </31>
            }
    
            {
                // <41>
                // Create service collection
                IServiceCollection serviceCollection = new ServiceCollection()
                    .AddHandlers(ServiceHandlers.Instance.ServiceRequestHandler)
                    .AddSingleton<string>("Hello")
                    .AddSingleton<string>("World")
                    .AddHandler(new StringsService());
                // Create service provider
                using var service = serviceCollection.BuildAvalancheServiceProvider();
                // Request service IEnumerable<string>
                IEnumerable<string> strings = service.GetRequiredService<IEnumerable<string>>();
                // Print four strings
                foreach (var str in strings) Console.WriteLine(str);
                // "Participated in service request (first line)"
                // "Hello"
                // "World"
                // "Participated in service request(last line)"
                // </41>
            }
    
    
        }
    
        // <MyClass>
        /// <summary></summary>
        public class MyClass
        {
            /// <summary></summary>
            public MyClass()
            {
            }
        }
        // </MyClass>
    
        // <LargeListBuilder>
        /// <summary>Creates lists with huge initial capacity.</summary>
        public class LargeListBuilder : IHandlerBase
        {
            /// <summary>Constructs <![CDATA[List<>]]> instances</summary>
            ConstructorT<int, IList> listConstructor = new(typeof(List<>));
    
            /// <summary>Serve <![CDATA[ServiceRequest<List<>>]]></summary>
            public void Handle<T>(IQuery<TransientServiceRequest<List<T>>, IServiceList<List<T>>> query)
            {
                // Unexpected status
                if (query.Response.Status.ExcludeFlags() > EntryStatus.Value) return;
                // Get response container
                IServiceList<List<T>>? response = query.Response.Value<IServiceList<List<T>>>() ?? query.Response.PassValue<IServiceList<List<T>>>(new ServiceList<List<T>>());
    
                // Create List<T> with Capacity = 1_000_000
                IList largeList = listConstructor.Create(typeof(T), 1_000_000);
                // Append to result
                response.Add(largeList, new IServiceList.Line(Order: 0L, ToDispose: false));
            }
        }
        // </LargeListBuilder>
    
        // <42>
        /// <summary>Participate in <![CDATA[IEnumerable<string>]]> service request</summary>
        public class StringsService : IHandlerBase
        {
            /// <summary></summary>
            [Order(1000)] // After ServiceDescriptor (0)
            public void Handle(IQuery<SingletonServiceRequest<string>, IServiceList<string>> query)
            {
                // Unexpected status
                if (query.Response.Status.ExcludeFlags() > EntryStatus.Value) return;
                // Get response container
                IServiceList<string>? list = query.Response.Value<IServiceList<string>>() ?? query.Response.PassValue<IServiceList<string>>(new ServiceList<string>());
    
                // String to add to service enumeration
                string str = "Participated in service request (first line)";
                // Append as first result value (Order = long.MinValue)
                list.Add(str, new IServiceList.Line(Order: long.MinValue, ToDispose: false));
    
                // String to add to service enumeration
                str = "Participated in service request (last line)";
                // Append as last result value (Order = long.MaxValue)
                list.Add(str, new IServiceList.Line(Order: long.MaxValue, ToDispose: false));
            }
        }
        // </42>
    
    
    
    }
    
    
    In This Article
    Back to top Copyright © Toni Kalajainen