• Avalanche.Core
Search Results for

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IFieldAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • Dto
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • 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
        • IFloatingPointType
      • Dto
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • Enum
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
        • DtoTarget(IDataType)
        • IntermediateTarget
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
        • CustomAttributeUtilities
        • ToStringRequest
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystemBrowse
        • IFileSystemCreateDirectory
        • IFileSystemDelete
        • IFileSystemFileAttribute
        • IFileSystemMount
        • IFileSystemMove
        • IFileSystemObserve
        • IFileSystemOpenStream
        • IFileSystemOpenMemory
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Utilities
        • Dispose
        • FileDictionary
        • FileScanner
        • FilterEnumerable
        • OperationSession
        • PollingFilterWatchToken
        • VisitTree
      • Article
        • Examples
        • PrintTree
    • 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
        • Unicode.CLDR43
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Memory
      • Introduction
      • IMemory<T>
      • BlockMemory<T>
      • FileMemory
      • ListMemory<L, T>
      • MemoryMemory<T>
      • MMFMemory<T>
      • PointerMemory<T>
      • Slice<M, T>
      • StreamMemory
      • Concurrency
        • RWLockedMemory
        • SynchronizedMemory
      • Serialization
        • Benchmarks
        • Fixed<T>
        • Variable<T>
        • ZigZag<T>
        • StringEncoding
      • Articles
        • Fixed-size and Variable-sized
        • IBlockPool<T>
        • Print Tree
        • Read and Write events
        • Stream View
        • Zero Heap
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageDescriptionsBase
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Localization Templates
        • Logging
        • Validation
    • Avalanche.Module
      • Introduction
      • IServiceCollection
      • IServiceBuilder
      • IHostBuilder
      • Dependencies
    • Avalanche.Options
      • Introduction
      • OptionsExtensions
      • OptionsMonitorCast
    • Avalanche.Protobuf
      • Introduction
    • 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
        • ArrayList
        • ArrayUtilities
        • BijectionMap
        • CachedSelect
        • DictionaryAdapter
        • EnumerableExtensions
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • StructList
        • Tuples
        • TupleUtilities
      • 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
        • SharedResource
        • 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

    Exporting

    IHandlerBase can be exported as field.

    public class Module1
    {
        /// <summary>Singleton</summary>
        public static Module1 Instance { get; } = new();
    
        /// <summary>Export handler</summary>
        public TypeHandler typeHandler = new TypeHandler();
        /// <summary>Export pre-build action (Invoked only with IHostBuilder)</summary>
        public Action<IServiceBuilder> PreBuildAction = (IServiceBuilder sb) => WriteLine("DI Pre-Build");
        /// <summary>Export post-build action (Invoked only with IHostBuilder)</summary>
        public Func<IService, IService> PostBuildAction = (IService service) => { WriteLine("DI Post-Build"); return service; };
    }
    

    [Export<IHandlerBase>] can be attached on classes to be exported. The module must inherit IImportsAssembly<Module> to indicate that the assembly is to be scanned for exported classes.

    [Export<IHandlerBase>, Order(1000)]
    public class TypeHandler : IHandler<string, Type>
    {
        public void Handle(IQuery<string, Type> query)
        {
            // Already handled
            if (query.Handled()) return;
            // Find type
            Type? type = Type.GetType(query.Request);
            // No type found
            if (type == null) return;
            // Assign result
            query.Response.SetValue(type);
        }
    }
    
    public class Module2 : IImportsAssembly<Module2>
    {
        public static Module2 Instance { get; } = new();
    }
    

    Importing to IServiceBuilder

    IServiceBuilder can process module.

    // Initialize service builder
    IServiceBuilder serviceBuilder = new ServiceBuilder();
    serviceBuilder.HandlerSources.Add(Module2.Instance);
    // Build service
    IService service = serviceBuilder.Build();
    // Query
    Type type = service.GetRequired<string, Type>("System.String");
    Console.WriteLine(type.FullName);
    

    Services.Create() can process module.

    // Build service
    IService service = Services.Create(Module2.Instance);
    // Query
    Type type = service.GetRequired<string, Type>("System.String");
    Console.WriteLine(type.FullName);
    

    ModuleImport<IHandlerBase>.Cached[module] scans for IHandlerBase. It doesn't follow dependencies.

    IHandlerBase[] handlers = ModuleImport<IHandlerBase>.Cached[Module2.Instance];
    ServiceDescriptorInfo[] serviceDescriptors = ModuleImportServiceDescriptorInfo.Cached[Module2.Instance];
    IHandlerBase[] serviceHandlers = serviceDescriptors.Select(sd => sd.ToHandler()).ToArray();
    

    ModuleImportServiceDescriptorInfo.Cached[module] scans for [ServiceDescriptor] annotations.

    ServiceDescriptorInfo[] serviceDescriptors = ModuleImportServiceDescriptorInfo.Cached[Module2.Instance];
    IHandlerBase[] serviceHandlers = serviceDescriptors.Select(sd => sd.ToHandler()).ToArray();
    

    Importing to IHostBuilder

    HostingContainer.ModuleImportCached[Module.Instance] scans ServiceDescriptors and pre- and post-build actions.

    // Initialize host builder
    IHostBuilder hostBuilder = new HostBuilder();
    hostBuilder.UseServiceProviderFactory(HostServiceProviderFactory.Instance);
    HostingContainer.ModuleImportCached[Module1.Instance].WriteTo(hostBuilder);
    HostingContainer.ModuleImportCached[Module2.Instance].WriteTo(hostBuilder);
    // Build host
    IHost host = hostBuilder.Build();
    // Query service
    IService service = host.Services.GetRequiredService<IService>();
    Type type = service.GetRequired<string, Type>("System.String");
    Console.WriteLine(type.FullName);
    

    Full Example

    Full example
    using Avalanche.Hosting;
    using Avalanche.Module;
    using Avalanche.Service;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using static System.Console;
    
    public class servicebuilder
    {
        public static void Run()
        {
            {
                // <01>
                // Initialize service builder
                IServiceBuilder serviceBuilder = new ServiceBuilder();
                serviceBuilder.HandlerSources.Add(Module2.Instance);
                // Build service
                IService service = serviceBuilder.Build();
                // Query
                Type type = service.GetRequired<string, Type>("System.String");
                Console.WriteLine(type.FullName);
                // </01>
            }
            {
                // <02>
                // Build service
                IService service = Services.Create(Module2.Instance);
                // Query
                Type type = service.GetRequired<string, Type>("System.String");
                Console.WriteLine(type.FullName);
                // </02>
            }
            {
                // <03>
                IHandlerBase[] handlers = ModuleImport<IHandlerBase>.Cached[Module2.Instance];
                ServiceDescriptorInfo[] serviceDescriptors = ModuleImportServiceDescriptorInfo.Cached[Module2.Instance];
                IHandlerBase[] serviceHandlers = serviceDescriptors.Select(sd => sd.ToHandler()).ToArray();
                // </03>
            }
            {
                // <04>
                ServiceDescriptorInfo[] serviceDescriptors = ModuleImportServiceDescriptorInfo.Cached[Module2.Instance];
                IHandlerBase[] serviceHandlers = serviceDescriptors.Select(sd => sd.ToHandler()).ToArray();
                // </04>
            }
            {
                // <11>
                // Initialize host builder
                IHostBuilder hostBuilder = new HostBuilder();
                hostBuilder.UseServiceProviderFactory(HostServiceProviderFactory.Instance);
                HostingContainer.ModuleImportCached[Module1.Instance].WriteTo(hostBuilder);
                HostingContainer.ModuleImportCached[Module2.Instance].WriteTo(hostBuilder);
                // Build host
                IHost host = hostBuilder.Build();
                // Query service
                IService service = host.Services.GetRequiredService<IService>();
                Type type = service.GetRequired<string, Type>("System.String");
                Console.WriteLine(type.FullName);
                // </11>
            }
        }
    
        // <98>
        public class Module1
        {
            /// <summary>Singleton</summary>
            public static Module1 Instance { get; } = new();
    
            /// <summary>Export handler</summary>
            public TypeHandler typeHandler = new TypeHandler();
            /// <summary>Export pre-build action (Invoked only with IHostBuilder)</summary>
            public Action<IServiceBuilder> PreBuildAction = (IServiceBuilder sb) => WriteLine("DI Pre-Build");
            /// <summary>Export post-build action (Invoked only with IHostBuilder)</summary>
            public Func<IService, IService> PostBuildAction = (IService service) => { WriteLine("DI Post-Build"); return service; };
        }
        // </98>
    
        // <99>
        [Export<IHandlerBase>, Order(1000)]
        public class TypeHandler : IHandler<string, Type>
        {
            public void Handle(IQuery<string, Type> query)
            {
                // Already handled
                if (query.Handled()) return;
                // Find type
                Type? type = Type.GetType(query.Request);
                // No type found
                if (type == null) return;
                // Assign result
                query.Response.SetValue(type);
            }
        }
    
        public class Module2 : IImportsAssembly<Module2>
        {
            public static Module2 Instance { get; } = new();
        }
        // </99>
    
    }
    
    
    In This Article
    Back to top