예제 #1
0
        public DiagnosticsViewHandler(
            [NotNull] IDeploymentTargetReadService deploymentTargetReadService,
            [NotNull] MultiSourceKeyValueConfiguration configuration,
            [NotNull] IConfiguration aspNetConfiguration,
            [NotNull] LoggingLevelSwitch loggingLevelSwitch,
            [NotNull] EnvironmentConfiguration environmentConfiguration,
            IServiceProvider serviceProvider,
            ServiceDiagnostics serviceDiagnostics,
            ConfigurationInstanceHolder configurationInstanceHolder,
            ILogger logger,
            IApplicationSettingsStore settingsStore,
            IApplicationAssemblyResolver applicationAssemblyResolver,
            IDistributedCache distributedCache)
        {
            _deploymentTargetReadService = deploymentTargetReadService ??
                                           throw new ArgumentNullException(nameof(deploymentTargetReadService));
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));

            _aspNetConfiguration         = aspNetConfiguration ?? throw new ArgumentNullException(nameof(aspNetConfiguration));
            _loggingLevelSwitch          = loggingLevelSwitch ?? throw new ArgumentNullException(nameof(loggingLevelSwitch));
            _environmentConfiguration    = environmentConfiguration;
            _serviceProvider             = serviceProvider;
            _serviceDiagnostics          = serviceDiagnostics;
            _configurationInstanceHolder = configurationInstanceHolder;
            _logger        = logger;
            _settingsStore = settingsStore;
            _applicationAssemblyResolver = applicationAssemblyResolver;
            _distributedCache            = distributedCache;
        }
        public void ItShouldBeResolvableByInterfaceAndItsWrappedType()
        {
            var configurationInstanceHolder = new ConfigurationInstanceHolder();

            var configuration = new MyConfiguration(123);
            var namedInstance = new NamedInstance <MyConfiguration>(configuration, "myInstance");

            configurationInstanceHolder.Add(namedInstance);

            ServiceProvider serviceProvider = new ServiceCollection()
                                              .AddConfigurationInstanceHolder(configurationInstanceHolder)
                                              .BuildServiceProvider();

            var myConfiguration = serviceProvider.GetService <MyConfiguration>();

            Assert.NotNull(myConfiguration);
            Assert.Equal(123, myConfiguration.Id);

            var namedFromProviderInstance = serviceProvider.GetService <INamedInstance <MyConfiguration> >();

            Assert.NotNull(namedFromProviderInstance);
            Assert.Equal(123, namedFromProviderInstance.Value.Id);
            Assert.Equal("myInstance", namedFromProviderInstance.Name);
            Assert.Equal(namedInstance, namedFromProviderInstance);
        }
예제 #3
0
        public static IServiceCollection AddConfigurationInstanceHolder(
            this IServiceCollection services,
            ConfigurationInstanceHolder holder)
        {
            foreach (Type holderRegisteredType in holder.RegisteredTypes)
            {
                var genericType = typeof(INamedInstance <>).MakeGenericType(holderRegisteredType);

                foreach (KeyValuePair <string, object> instance in holder.GetInstances(holderRegisteredType))
                {
                    services.Add(new ServiceDescriptor(holderRegisteredType,
                                                       provider => instance.Value,
                                                       ServiceLifetime.Transient));

                    var concreteGenericType = typeof(NamedInstance <>).MakeGenericType(holderRegisteredType);

                    services.Add(new ServiceDescriptor(genericType,
                                                       provider => Activator.CreateInstance(concreteGenericType,
                                                                                            instance.Value,
                                                                                            instance.Key) ?? throw new InvalidOperationException(
                                                           $"Could not create type {concreteGenericType.FullName}"),
                                                       ServiceLifetime.Transient));
                }
            }

            return(services);
        }
예제 #4
0
        public static void ConfigureEnvironment(ConfigurationInstanceHolder configurationInstanceHolder)
        {
            if (configurationInstanceHolder is null)
            {
                throw new ArgumentNullException(nameof(configurationInstanceHolder));
            }

            var configureEnvironments    = configurationInstanceHolder.CreateInstances <IConfigureEnvironment>();
            var environmentConfiguration = configurationInstanceHolder.Get <EnvironmentConfiguration>();

            if (environmentConfiguration is null)
            {
                var newConfiguration = new EnvironmentConfiguration();
                environmentConfiguration = newConfiguration;

                configurationInstanceHolder.Add(
                    new NamedInstance <EnvironmentConfiguration>(newConfiguration, "default"));
            }

            var ordered = configureEnvironments
                          .Select(environmentConfigurator => (EnvironmentConfigurator: environmentConfigurator,
                                                              Order: environmentConfigurator.GetRegistrationOrder(0))).OrderBy(pair => pair.Order)
                          .Select(pair => pair.EnvironmentConfigurator).ToArray();

            foreach (var configureEnvironment in ordered)
            {
                configureEnvironment.Configure(environmentConfiguration);
            }
        }
        public static void AddInstance <T>(this ConfigurationInstanceHolder holder, [NotNull] T instance) where T : class
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            holder.Add(new NamedInstance <T>(instance, instance.GetType().FullName !));
        }
        public static object?Create(this ConfigurationInstanceHolder holder, Type type)
        {
            var instances = holder.GetInstances(type);

            if (instances.Count == 1)
            {
                return(instances.Values.FirstOrDefault());
            }

            if (instances.Count > 1)
            {
                throw new InvalidOperationException($"Found multiple instances of type {type.FullName}");
            }

            var constructors = type.GetConstructors();

            if (constructors.Length != 1)
            {
                throw new InvalidOperationException($"The type {type.FullName} has multiple constructors");
            }

            var constructorInfo = constructors[0];

            var parameters = constructorInfo.GetParameters();

            var missingArgs = parameters.Where(p =>
                                               !holder.RegisteredTypes.Any(registeredType => p.ParameterType.IsAssignableFrom(registeredType)) &&
                                               !p.IsOptional).ToArray();

            var optionalArgs = parameters.Where(p =>
                                                !holder.RegisteredTypes.Any(registeredType => p.ParameterType.IsAssignableFrom(registeredType)) &&
                                                p.IsOptional).ToArray();

            if (missingArgs.Length > 0)
            {
                throw new InvalidOperationException(
                          $"Missing types defined in ctor for type {type.FullName}: {string.Join(", ", missingArgs.Select(m => m.ParameterType.FullName))}");
            }

            object?GetArgumentValue(ParameterInfo parameter)
            {
                object?value = optionalArgs.Contains(parameter)
                    ? null
                    : holder.GetInstances(
                    holder.RegisteredTypes.Single(reg => parameter.ParameterType.IsAssignableFrom(reg)))
                               .Single()
                               .Value;

                return(value);
            }

            object?[] args = parameters.Length == 0
                ? Array.Empty <object>()
                : parameters.Select(GetArgumentValue).ToArray();

            return(Activator.CreateInstance(type, args));
        }
예제 #7
0
        public void WhenRegisteringSingleInstanceTryGet()
        {
            var holder   = new ConfigurationInstanceHolder();
            var instance = new ValidatableOptional("abc", 123);

            holder.Add(new NamedInstance <ValidatableOptional>(instance, "abc-instance"));

            bool found = holder.TryGet("abc-instance", out ValidatableOptional? foundInstance);

            Assert.True(found);
            Assert.Same(instance, foundInstance);
        }
 public AgentPreStartModule(IServiceProvider provider,
                            EnvironmentConfiguration environmentConfiguration)
 {
     if (environmentConfiguration.HttpEnabled)
     {
         _seq                 = provider.GetRequiredService <SeqArgs>();
         _provider            = provider;
         _serverConfiguration = provider.GetRequiredService <ServerEnvironmentTestConfiguration>();
         _testConfiguration   = provider.GetRequiredService <TestConfiguration>();
         _holder              = provider.GetRequiredService <ConfigurationInstanceHolder>();
     }
 }
예제 #9
0
        public UserConfigUpdater(ConfigurationInstanceHolder configurationHolder,
                                 EnvironmentConfiguration applicationEnvironment)
        {
            _configurationHolder = configurationHolder;

            _fileName = Path.Combine(applicationEnvironment.ContentBasePath ?? Directory.GetCurrentDirectory(),
                                     "config.user");

            if (File.Exists(_fileName))
            {
                var fileInfo = new FileInfo(_fileName);

                if (fileInfo.Directory is { })
예제 #10
0
        public void CreateTypeWithSingletons()
        {
            var holder = new ConfigurationInstanceHolder();

            holder.AddInstance(new EnvironmentConfiguration {
                ApplicationBasePath = @"C:\app"
            });

            EnvironmentConsumer environmentConsumer = holder.Create <EnvironmentConsumer>();

            Assert.NotNull(environmentConsumer);
            Assert.NotNull(environmentConsumer.EnvironmentConfiguration);
            Assert.Equal(@"C:\app", environmentConsumer.EnvironmentConfiguration.ApplicationBasePath);
        }
예제 #11
0
        public void WhenRegisteringSingleInstance()
        {
            var holder = new ConfigurationInstanceHolder();

            holder.Add(new NamedInstance <ValidatableOptional>(new ValidatableOptional("abc", 123), "abc-instance"));

            ImmutableDictionary <string, ValidatableOptional?> instances = holder.GetInstances <ValidatableOptional>();

            Assert.Single(instances);

            Assert.Equal("abc-instance", instances.Keys.Single());
            Assert.Equal("abc", instances["abc-instance"].Name);
            Assert.Equal(123, instances["abc-instance"].Value);
        }
        public static IEnumerable <T> CreateInstances <T>(this ConfigurationInstanceHolder holder) where T : class
        {
            var registeredTypes = holder.RegisteredTypes
                                  .Where(registered =>
                                         typeof(T).IsAssignableFrom(registered) && !registered.IsAbstract)
                                  .ToArray();

            foreach (Type registeredType in registeredTypes)
            {
                foreach (T instance in holder.GetInstances(registeredType).Values.OfType <T>())
                {
                    yield return(instance);
                }
            }
        }
예제 #13
0
 public DeploymentWorkerService(
     ConfigurationInstanceHolder configurationInstanceHolder,
     ILogger logger,
     IMediator mediator,
     AgentsData agents,
     TimeoutHelper timeoutHelper)
 {
     _configurationInstanceHolder = configurationInstanceHolder;
     _logger        = logger;
     _mediator      = mediator;
     _agents        = agents;
     _timeoutHelper = timeoutHelper;
     _tasks         = new Dictionary <DeploymentTargetId, Task>();
     _cancellations = new Dictionary <DeploymentTargetId, CancellationTokenSource>();
 }
예제 #14
0
        private static Task <App <T> > BuildAppAsync(CancellationTokenSource cancellationTokenSource,
                                                     string[] commandLineArgs,
                                                     IReadOnlyDictionary <string, string> environmentVariables,
                                                     IReadOnlyCollection <Assembly> scanAssemblies,
                                                     params object[] instances)
        {
            MultiSourceKeyValueConfiguration startupConfiguration =
                ConfigurationInitialization.InitializeStartupConfiguration(commandLineArgs,
                                                                           environmentVariables,
                                                                           scanAssemblies);

            ConfigurationInstanceHolder configurationInstanceHolder =
                GetConfigurationRegistrations(startupConfiguration, scanAssemblies);

            var assemblyResolver = new InstanceApplicationAssemblyResolver(scanAssemblies.SafeToImmutableArray());

            configurationInstanceHolder.AddInstance(assemblyResolver);

            configurationInstanceHolder.AddInstance(configurationInstanceHolder);

            foreach (object instance in instances.NotNull())
            {
                configurationInstanceHolder.AddInstance(instance);
            }

            var loggingLevelSwitch = new LoggingLevelSwitch();

            configurationInstanceHolder.AddInstance(loggingLevelSwitch);
            configurationInstanceHolder.AddInstance(cancellationTokenSource);

            ApplicationPaths paths =
                configurationInstanceHolder.GetInstances <ApplicationPaths>().SingleOrDefault().Value ??
                new ApplicationPaths();

            AppPathHelper.SetApplicationPaths(paths, commandLineArgs);

            if (paths.BasePath is null)
            {
                throw new InvalidOperationException("Base path is not set");
            }

            var startupLoggerConfigurationHandlers = assemblyResolver.GetAssemblies()
                                                     .GetLoadablePublicConcreteTypesImplementing <
                IStartupLoggerConfigurationHandler>()
                                                     .Select(type =>
                                                             configurationInstanceHolder.Create(type) as
                                                             IStartupLoggerConfigurationHandler)
                                                     .Where(item => item is { }).ToImmutableArray();
예제 #15
0
 public WorkerLifetimeManager(
     ConfigurationInstanceHolder configurationInstanceHolder,
     WorkerConfiguration workerConfiguration,
     IMediator mediator,
     ILogger logger,
     TimeoutHelper timeoutHelper,
     ICustomClock clock,
     IServiceProvider serviceProvider)
 {
     _configurationInstanceHolder = configurationInstanceHolder;
     _workerConfiguration         = workerConfiguration;
     _mediator        = mediator;
     _logger          = logger;
     _timeoutHelper   = timeoutHelper;
     _clock           = clock;
     _serviceProvider = serviceProvider;
 }
예제 #16
0
        public void WhenRemovingNonExistingType()
        {
            var holder = new ConfigurationInstanceHolder();

            holder.Add(new NamedInstance <ValidatableOptional>(new ValidatableOptional("abc", 123), "abc-instance"));

            bool found = holder.TryGet("abc-instance", out ValidatableOptional? instance);

            Assert.True(found);

            Assert.NotNull(instance);

            bool isRemoved = holder.TryRemove("abc-instance", typeof(string), out object?removed);

            Assert.False(isRemoved);

            Assert.Null(removed);
        }
예제 #17
0
        public App(IHostBuilder hostBuilder,
                   CancellationTokenSource cancellationTokenSource,
                   ILogger appLogger,
                   MultiSourceKeyValueConfiguration configuration,
                   IReadOnlyCollection <Assembly> scanAssemblies,
                   ConfigurationInstanceHolder configurationInstanceHolder)
        {
            CancellationTokenSource = cancellationTokenSource ??
                                      throw new ArgumentNullException(nameof(cancellationTokenSource));

            Logger         = appLogger ?? throw new ArgumentNullException(nameof(appLogger));
            Configuration  = configuration;
            ScanAssemblies = scanAssemblies.SafeToImmutableArray();
            ConfigurationInstanceHolder = configurationInstanceHolder;
            HostBuilder     = hostBuilder ?? throw new ArgumentNullException(nameof(hostBuilder));
            _instanceId     = Guid.NewGuid();
            ApplicationName = configuration.GetApplicationName();
            AppInstance     = ApplicationName + " " + _instanceId;
        }
예제 #18
0
        public void WhenRegisteringMultipleInstances()
        {
            var holder = new ConfigurationInstanceHolder();

            holder.Add(new NamedInstance <ValidatableOptional>(new ValidatableOptional("abc", 123), "abc-instance"));
            holder.Add(new NamedInstance <ValidatableOptional>(new ValidatableOptional("def", 234), "def-instance"));

            ImmutableDictionary <string, ValidatableOptional?> instances = holder.GetInstances <ValidatableOptional>();

            Assert.Equal(2, instances.Count);

            Assert.Contains("abc-instance", instances.Keys);
            Assert.Equal("abc", instances["abc-instance"].Name);
            Assert.Equal(123, instances["abc-instance"].Value);

            Assert.Contains("def-instance", instances.Keys);
            Assert.Equal("def", instances["def-instance"].Name);
            Assert.Equal(234, instances["def-instance"].Value);
        }
 public WorkerSetupStartupTask(
     IKeyValueConfiguration configuration,
     ILogger logger,
     IDeploymentTargetReadService deploymentTargetReadService,
     ConfigurationInstanceHolder holder,
     IMediator mediator,
     WorkerConfiguration workerConfiguration,
     TimeoutHelper timeoutHelper,
     ICustomClock clock,
     IServiceProvider serviceProvider)
 {
     _configuration = configuration;
     _logger        = logger;
     _deploymentTargetReadService = deploymentTargetReadService;
     _holder              = holder;
     _mediator            = mediator;
     _workerConfiguration = workerConfiguration;
     _timeoutHelper       = timeoutHelper;
     _clock           = clock;
     _serviceProvider = serviceProvider;
 }
예제 #20
0
        public object Diagnostics(
            [FromServices] ConfigurationInstanceHolder configurationInstanceHolder,
            [FromServices] IEnumerable <MySampleMultipleInstance> multipleInstances)
        {
            if (configurationInstanceHolder is null)
            {
                throw new ArgumentNullException(nameof(configurationInstanceHolder));
            }

            if (multipleInstances is null)
            {
                throw new ArgumentNullException(nameof(multipleInstances));
            }

            return(new
            {
                Instances = configurationInstanceHolder !.RegisteredTypes
                            .Select(type => new
                {
                    type.FullName, Instances = configurationInstanceHolder.GetInstances(type).ToArray()
                })
                            .ToArray(),
                multipleInstances
            });
예제 #21
0
 public DevEnvironmentConfigurator(ConfigurationInstanceHolder holder) => _agentId = holder.GetInstances <AgentId>().SingleOrDefault().Value;
 public static T Create <T>(this ConfigurationInstanceHolder holder) where T : class =>
 (T)Create(holder, typeof(T)) !;
 public static T?Get <T>(this ConfigurationInstanceHolder holder) where T : class =>
 holder.GetInstances <T>().SingleOrDefault().Value;