• 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.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
    • 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.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
      • 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
      • String
        • IEscaper
        • UnicodeString
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    Scope

    Services can be composed to use different scopes. Local scoped service can be created for a specific purpose, and be thrown away once purpose is completed.

    In the following example TypeRequest is handled and cached in applicationScope and TypeBuilderRequest by buildScope. After building a type, the builder classes are discarded.

    // Create application-scope service with cache
    IService applicationScope = Services.Create(ServiceHandlers.Instance);
    // Place instance here
    object instance;
    // Temporary scope for building 'instance'
    {
        // Create build scoped service with cache to be disposed
        using var buildScope = Services.Create((applicationScope, EmitHandlers.Instance, RequestHandlers.Instance));
        // Create type building request
        IRequestFor<TypeBuilder> typeBuilder = new TypeBuilderRequest("HelloWorldClass");
        // Add ToString() -method
        typeBuilder = typeBuilder.Append(ToStringRequest.Create("Hello World"));
        // Type request
        IRequestFor<Type> typeRequest = new TypeRequest(typeBuilder);
        // Instance request
        IRequestFor<object> newRequest = new NewRequest(typeRequest);
        // Create instance
        instance = buildScope.GetRequired<IRequestFor<object>, object>(newRequest);
    }
    // Scope is closed and type builder is disposed, type and instance remain in 'applicationScope'.
    Console.WriteLine(instance);
    

    Request as a tree, and by cache location.

    ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ applicationScope ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
    NewRequest
    └── Type = TypeRequest
    ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ buildScope ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
        └── Name = ContextRequest
            ├── Key = "System.Reflection.Emit.TypeBuilder"
            ├── Value = TypeBuilderRequest
            │   └── Name = "HelloWorldClass"
            └── Requests[0] = BatchRequest
                ├── Requests[0] = Emit
                │   ├── Opcode = ldstr
                │   ├── Parameters[0] = "Hello World"
                │   └── ILGenerator = ILGeneratorRequest
                │       └── Builder = MethodBuilderRequest
                │           ├── Name = "ToString"
                │           ├── Attributes = PrivateScope, Public, Virtual, HideBySig
                │           └── ReturnType = System.String
                └── Requests[1] = Emit
                    ├── Opcode = ret
                    └── ILGenerator = ILGeneratorRequest
    ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
    

    Scoped Services

    Another way to create scope is with IServiceScopeFactory service. It uses transient cache for all locally constructed instances except those that have ServiceDescription at ServiceLifetime.Singleton lifetime. They are constructed, cached and disposed at parent service.

    // Create application-scope service with cache
    IService applicationScope = Services.Create((ServiceHandlers.Instance, ServiceScopeHandler.Instance, EmitHandlers.Instance, RequestHandlers.Instance));
    // Place instance here
    object instance;
    // Temporary scope for building 'instance'
    {
        // Create transient scope
        using IServiceScope scope = ((IServiceScopeFactory)applicationScope.GetService(typeof(IServiceScopeFactory))!).CreateScope();
        // Create service
        IService scopedService = (IService)scope.ServiceProvider;
        // Create request
        IRequestFor<TypeBuilder> typeBuilder = new TypeBuilderRequest("HelloWorldClass");
        // Add ToString() -method
        typeBuilder = typeBuilder.Append(ToStringRequest.Create("Hello World"));
        // Type request
        IRequestFor<Type> typeRequest = new TypeRequest(typeBuilder);
        // Instance request
        IRequestFor<object> newRequest = new NewRequest(typeRequest);
        // Create instance
        instance = scopedService.GetRequired<IRequestFor<object>, object>(newRequest);
    }
    // Scope is closed and type builder is disposed, type and instance remain in 'applicationScope'.
    Console.WriteLine(instance);
    

    Full Example

    Full example
    using System;
    using System.Collections.Generic;
    using System.Reflection.Emit;
    using Avalanche.Emit;
    using Avalanche.Service;
    using Microsoft.Extensions.DependencyInjection;
    
    public class service_scope
    {
        public static void Run()
        {
            {
                // <01>
                // Create application-scope service with cache
                IService applicationScope = Services.Create(ServiceHandlers.Instance);
                // Place instance here
                object instance;
                // Temporary scope for building 'instance'
                {
                    // Create build scoped service with cache to be disposed
                    using var buildScope = Services.Create((applicationScope, EmitHandlers.Instance, RequestHandlers.Instance));
                    // Create type building request
                    IRequestFor<TypeBuilder> typeBuilder = new TypeBuilderRequest("HelloWorldClass");
                    // Add ToString() -method
                    typeBuilder = typeBuilder.Append(ToStringRequest.Create("Hello World"));
                    // Type request
                    IRequestFor<Type> typeRequest = new TypeRequest(typeBuilder);
                    // Instance request
                    IRequestFor<object> newRequest = new NewRequest(typeRequest);
                    // Create instance
                    instance = buildScope.GetRequired<IRequestFor<object>, object>(newRequest);
                }
                // Scope is closed and type builder is disposed, type and instance remain in 'applicationScope'.
                Console.WriteLine(instance);
                // </01>
    
                // Get cache
                (applicationScope as IEntryProviderBase).TryGetEntryCache(out IEntryCacheBase? cache);
                // Disconnect all cache lines
                cache!.TryDisconnectAll(out System.Collections.Generic.IEnumerable<KeyValuePair<object, IEntry>>? cacheLines);
                //
                foreach (var line in cacheLines!)
                {
                    Console.WriteLine(line);
                }
            }
    
            {
                // <02>
                // Create a service with cache
                IService applicationScope = Services.Create(ServiceHandlers.Instance);
                // Temporary scope
                {
                    // Create build scoped service with cache to be disposed
                    using var buildScope = Services.Create((applicationScope, EmitHandlers.Instance, RequestHandlers.Instance));
                    // Print service as tree
                    Console.WriteLine(buildScope.ToString());
                }
                // </02>
            }
    
            {
                // <03>
                // Create application-scope service with cache
                IService applicationScope = Services.Create((ServiceHandlers.Instance, ServiceScopeHandler.Instance, EmitHandlers.Instance, RequestHandlers.Instance));
                // Place instance here
                object instance;
                // Temporary scope for building 'instance'
                {
                    // Create transient scope
                    using IServiceScope scope = ((IServiceScopeFactory)applicationScope.GetService(typeof(IServiceScopeFactory))!).CreateScope();
                    // Create service
                    IService scopedService = (IService)scope.ServiceProvider;
                    // Create request
                    IRequestFor<TypeBuilder> typeBuilder = new TypeBuilderRequest("HelloWorldClass");
                    // Add ToString() -method
                    typeBuilder = typeBuilder.Append(ToStringRequest.Create("Hello World"));
                    // Type request
                    IRequestFor<Type> typeRequest = new TypeRequest(typeBuilder);
                    // Instance request
                    IRequestFor<object> newRequest = new NewRequest(typeRequest);
                    // Create instance
                    instance = scopedService.GetRequired<IRequestFor<object>, object>(newRequest);
                }
                // Scope is closed and type builder is disposed, type and instance remain in 'applicationScope'.
                Console.WriteLine(instance);
                // </03>
            }
        }
    }
    
    
    In This Article
    Back to top Copyright © Toni Kalajainen