// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; namespace Microsoft.ML.OnnxRuntime { /// /// Helper to allow the creation/addition of session options based on pre-defined named entries. /// public static class SessionOptionsContainer { static Lazy> _defaultHandler; static readonly Dictionary>> _configurationHandlers = new Dictionary>>(); static Lazy> DefaultHandler => _defaultHandler != null ? _defaultHandler : (_defaultHandler = new Lazy>(() => (options) => { /* use as is */ })); /// /// Register the default handler. This is used when a configuration name is not provided. /// /// Handler that applies the default settings to a SessionOptions instance. /// public static void Register(Action defaultHandler) => _defaultHandler = new Lazy>(() => defaultHandler); /// /// Register a named handler. /// /// Configuration name. /// /// Handler that applies the settings for the configuration to a SessionOptions instance. /// public static void Register(string configuration, Action handler) => _configurationHandlers[configuration] = new Lazy>(() => handler); /// /// Create a SessionOptions instance with configuration applied. /// /// /// Configuration to use. /// If not provided, the default set of session options will be applied if useDefaultAsFallback is true. /// /// /// If configuration is not provided or not found, use the default session options. /// /// SessionOptions with configuration applied. public static SessionOptions Create(string configuration = null, bool useDefaultAsFallback = true) => new SessionOptions().ApplyConfiguration(configuration, useDefaultAsFallback); /// /// Reset by removing all registered handlers. /// public static void Reset() { _defaultHandler = null; _configurationHandlers.Clear(); } /// /// Apply a configuration to a SessionOptions instance. /// /// SessionOptions to apply configuration to. /// Configuration to use. /// /// Use the default configuration if 'configuration' is not provided or not found. /// /// Updated SessionOptions instance. public static SessionOptions ApplyConfiguration(this SessionOptions options, string configuration = null, bool useDefaultAsFallback = true) { var handler = Resolve(configuration, useDefaultAsFallback); handler(options); return options; } static Action Resolve(string configuration = null, bool useDefaultAsFallback = true) { if (string.IsNullOrWhiteSpace(configuration)) return DefaultHandler.Value; if (_configurationHandlers.TryGetValue(configuration, out var handler)) return handler.Value; if (useDefaultAsFallback) return DefaultHandler.Value; throw new KeyNotFoundException($"Configuration not found for '{configuration}'"); } } }