/// <inheritdoc/> public void Initialize() { var handlers = _typeFinder.FindMultiple(typeof(ICanHandle <>)); handlers.ForEach(_ => SetupSubscriptionFor(_, typeof(ICanHandle <>))); var dataPointHandlers = _typeFinder.FindMultiple(typeof(ICanHandleDataPoint <>)); dataPointHandlers.ForEach(_ => SetupSubscriptionFor(_, typeof(ICanHandleDataPoint <>), typeof(DataPoint <>))); }
void PopulateFilterValidatorMap() { _typeFinder.FindMultiple <IFilterDefinition>().ForEach(filterDefinitionType => { if (TryGetValidatorTypeFor(filterDefinitionType, out var validatorType)) { _logger.Trace("Filter definition type {FilterType} can be validated by validator type {ValidatorType}", filterDefinitionType, validatorType); _filterDefinitionToValidatorMap.TryAdd(filterDefinitionType, validatorType); } }); }
void InitializeCommandValidators() { _inputCommandValidators = new Dictionary <Type, Type>(); _businessCommandValidators = new Dictionary <Type, Type>(); var commandInputValidators = _typeFinder.FindMultiple(_commandInputValidatorType); var commandBusinessValidators = _typeFinder.FindMultiple(_commandBusinessValidatorType); commandInputValidators.ForEach(type => RegisterCommandValidator(type, _inputCommandValidators)); commandBusinessValidators.ForEach(type => RegisterCommandValidator(type, _businessCommandValidators)); }
/// <inheritdoc/> public Type Resolve(IApplicationResourceIdentifier identifier) { _logger.Trace($"Trying to resolve : {identifier.Resource.Name} - with type {identifier.Resource.Type.Identifier}"); var typeIdentifier = identifier.Resource.Type.Identifier; if (_resolversByType.ContainsKey(typeIdentifier)) { return(_resolversByType[typeIdentifier].Resolve(identifier)); } var resourceType = _types.GetFor(typeIdentifier); var types = _typeFinder.FindMultiple(resourceType.Type); var typesMatchingName = types.Where(t => t.Name == identifier.Resource.Name); ThrowIfAmbiguousTypes(identifier, typesMatchingName); var formats = _application.Structure.GetStructureFormatsForArea(resourceType.Area); var type = typesMatchingName.Where(t => formats.Any(f => f.Match(t.Namespace).HasMatches)).FirstOrDefault(); if (type != null) { return(type); } _logger.Error($"Unknown application resurce type : {identifier.Resource.Type.Identifier}"); throw new UnknownApplicationResourceType(identifier.Resource.Type.Identifier); }
public GeneratedProxies( CommandProxies commandProxies, CommandSecurityProxies commandSecurityProxies, QueryProxies queryProxies, ReadModelProxies readModelProxies, ServiceProxies serviceProxies, NamespaceConfigurationProxies namespaceConfigurationProxies, #if (NET461) HubProxies hubProxies, #endif ITypeFinder typeFinder, IContainer container) { var builder = new StringBuilder(); builder.Append(commandProxies.Generate()); builder.Append(commandSecurityProxies.Generate()); builder.Append(readModelProxies.Generate()); builder.Append(queryProxies.Generate()); builder.Append(serviceProxies.Generate()); builder.Append(namespaceConfigurationProxies.Generate()); #if (NET461) builder.Append(hubProxies.Generate()); #endif var generatorTypes = typeFinder.FindMultiple <IProxyGenerator>().Where(t => !t.Namespace.StartsWith("Dolittle")); foreach (var generatorType in generatorTypes) { var generator = container.Get(generatorType) as IProxyGenerator; builder.Append(generator.Generate()); } All = builder.ToString(); }
void PopulateEventProcessors() { var processors = _typeFinder.FindMultiple <IProcessEvents>(); foreach (var processor in processors) { var methods = processor.GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(m => { var parameters = m.GetParameters(); return (m.Name.Equals(ProcessMethodName) && parameters.Length == 1 && typeof(IEvent).GetTypeInfo().IsAssignableFrom(parameters[0].ParameterType.GetTypeInfo())); }); foreach (var method in methods) { var eventProcessorTypeIdentifier = _applicationResources.Identify(processor); var eventProcessorTypeIdentifierAsString = _applicationResourcesIdentifierConverter.AsString(eventProcessorTypeIdentifier); var eventIdentifier = _applicationResources.Identify(method.GetParameters()[0].ParameterType); var eventIdentifierAsString = _applicationResourcesIdentifierConverter.AsString(eventIdentifier); var eventProcessorIdentifier = (EventProcessorIdentifier)$"{eventProcessorTypeIdentifierAsString}{IdentifierSeparator}{eventIdentifierAsString}"; var processMethodEventProcessor = new ProcessMethodEventProcessor(_container, _systemClock, eventProcessorIdentifier, eventIdentifier, method); _eventProcessors.Add(processMethodEventProcessor); } } }
/// <summary> /// Initializes a new instance of <see cref="ConfigurationFileParsers"/> /// </summary> /// <param name="typeFinder"><see cref="ITypeFinder"/> to use for finding parsers</param> /// <param name="container"><see cerf="IContainer"/> used to get instances</param> public ConfigurationFileParsers(ITypeFinder typeFinder, IContainer container) { _typeFinder = typeFinder; _parsers = typeFinder .FindMultiple <ICanParseConfigurationFile>() .Select(_ => container.Get(_) as ICanParseConfigurationFile); }
/// <inheritdoc/> public void Perform() { var configurationClasses = _typeFinder.FindMultiple <RaaLabs.TimeSeries.Modules.ITriggerAppRestartOnChange>(); var filenames = configurationClasses .Where(_ => _fileProvider.CanProvide(_)) .Select(clazz => (clazz, attribute: clazz.GetCustomAttribute <NameAttribute>(true))) .Select(cc => (cc.clazz, cc.attribute.Name)) .ToArray(); var pwd = Directory.GetCurrentDirectory(); var filesToWatch = filenames.Select(_ => (_.clazz, path: FindConfigurationFilePath(_.Name))).ToArray(); // Neither FileSystemWatcher nor PhysicalFileProvider have worked platform-independently at watching files asynchronously, // not even with DOTNET_USE_POLLING_FILE_WATCHER=1. Because of this, we will watch all configuration files manually instead. _watcherThread = new Thread(_ => { var filesChangedAt = filesToWatch.ToDictionary(file => file.path, file => File.GetLastWriteTimeUtc(file.path)); while (true) { if (filesChangedAt.Any(file => File.GetLastWriteTimeUtc(file.Key) != file.Value)) { _logger.Information($"Configuration changed, restarting application..."); Environment.Exit(0); } Thread.Sleep(5_000); } }); _watcherThread.Start(); }
void DiscoverBootStages(ITypeFinder typeFinder) { var bootStagePerformerTypes = typeFinder.FindMultiple <ICanPerformPartOfBootStage>(); var bootStagePerformers = bootStagePerformerTypes .Where(_ => !_initialFixedStages.Any(existing => existing.GetType() == _)) .Select(_ => { ThrowIfMissingDefaultConstructorForBootStagePerformer(_); if (_container != null) { return(_container.Get(_) as ICanPerformPartOfBootStage); } return(Activator.CreateInstance(_) as ICanPerformPartOfBootStage); }) .OrderBy(_ => _.BootStage); bootStagePerformers.GroupBy(performer => performer.BootStage).ForEach(performers => { var beforePerformers = performers.Where(_ => HasInterface(_, typeof(ICanRunBeforeBootStage <>))); beforePerformers.ForEach(_stages.Enqueue); var performer = performers.Single(_ => HasInterface(_, typeof(ICanPerformBootStage <>))); _stages.Enqueue(performer); var afterPerformers = performers.Where(_ => HasInterface(_, typeof(ICanRunAfterBootStage <>))); afterPerformers.ForEach(_stages.Enqueue); }); ThrowIfMissingBootStage(bootStagePerformers); }
void Initialize() { _logger.Debug("Initializing command handlers"); var handlers = _typeFinder.FindMultiple <ICanHandleCommands>(); handlers.ForEach(Register); }
/// <inheritdoc/> public IBindingCollection DiscoverAndSetupBindings() { _logger.Trace("Discover and setup bindings"); var bindingCollections = new ConcurrentBag <IBindingCollection>(); var allTypes = _typeFinder.All; _logger.Trace("Find all binding conventions"); var conventionTypes = _typeFinder.FindMultiple <IBindingConvention>(); _scheduler.PerformForEach(conventionTypes, (Action <Type>)(conventionType => { _logger.Trace((string)$"Handle convention type {conventionType.AssemblyQualifiedName}"); var convention = _bootContainer.Get(conventionType) as IBindingConvention; var servicesToResolve = allTypes.Where(service => convention.CanResolve(service)); var bindings = new ConcurrentBag <Binding>(); _scheduler.PerformForEach(servicesToResolve, service => { var bindingBuilder = new BindingBuilder(Binding.For(service)); convention.Resolve(service, bindingBuilder); bindings.Add(bindingBuilder.Build()); }); var bindingCollection = new BindingCollection(bindings); bindingCollections.Add(bindingCollection); })); var aggregatedBindingCollection = new BindingCollection(bindingCollections.ToArray()); return(aggregatedBindingCollection); }
bool HasDefaultConfigurationProviderFor(Type type) { var providerType = typeof(ICanProvideDefaultConfigurationFor <>).MakeGenericType(type); var actualTypes = _typeFinder.FindMultiple(providerType); ThrowIfMultipleDefaultProvidersFound(type, actualTypes); return(actualTypes.Count() == 1); }
void PopulateSecurityDescriptors() { var securityDescriptorTypes = _typeFinder.FindMultiple <ISecurityDescriptor>(); var instances = new List <ISecurityDescriptor>(); instances.AddRange(securityDescriptorTypes.Select(t => _container.Get(t) as ISecurityDescriptor)); _securityDescriptors = instances; }
public string Generate() { var typesByNamespace = _typeFinder .FindMultiple <ICommand>() .Where(t => !CommandProxies._namespacesToExclude.Any(n => t.Namespace.StartsWith(n))) .GroupBy(t => t.Namespace); var result = new StringBuilder(); var globalCommands = _codeGenerator.Namespace(Namespaces.COMMANDS); foreach (var @namespace in typesByNamespace) { Namespace currentNamespace; if (_configuration.NamespaceMapper.CanResolveToClient(@namespace.Key)) { currentNamespace = _codeGenerator.Namespace(_configuration.NamespaceMapper.GetClientNamespaceFrom(@namespace.Key)); } else { currentNamespace = globalCommands; } foreach (var type in @namespace) { if (type.GetTypeInfo().IsGenericType) { continue; } var identifier = _applicationResources.Identify(type); var command = new CommandRequest(TransactionCorrelationId.NotSet, identifier, new Dictionary <string, object>()); var authorizationResult = _commandSecurityManager.Authorize(command); var name = $"{type.Name.ToCamelCase()}SecurityContext"; currentNamespace.Content.Assign(name) .WithType(t => t .WithSuper("Dolittle.commands.CommandSecurityContext") .Function .Body .Variant("self", v => v.WithThis()) .Access("this", a => a .WithFunctionCall(f => f .WithName("isAuthorized") .WithParameters(authorizationResult.IsAuthorized.ToString().ToCamelCase()) ) ) ); } if (currentNamespace != globalCommands) { result.Append(_codeGenerator.GenerateFrom(currentNamespace)); } } result.Append(_codeGenerator.GenerateFrom(globalCommands)); return(result.ToString()); }
void Initialize() { var migratorTypes = _typeFinder.FindMultiple(typeof(IEventMigrator <,>)); foreach (var migrator in migratorTypes) { RegisterMigrator(migrator); } }
public string Generate() { var typesByNamespace = _typeFinder.FindMultiple <ICommand>().Where(t => !_namespacesToExclude.Any(n => t.Namespace.StartsWith(n))).GroupBy(t => t.Namespace); var result = new StringBuilder(); Namespace currentNamespace; Namespace globalCommands = _codeGenerator.Namespace(Namespaces.COMMANDS); foreach (var @namespace in typesByNamespace) { if (_configuration.NamespaceMapper.CanResolveToClient(@namespace.Key)) { currentNamespace = _codeGenerator.Namespace(_configuration.NamespaceMapper.GetClientNamespaceFrom(@namespace.Key)); } else { currentNamespace = globalCommands; } foreach (var type in @namespace) { if (type.GetTypeInfo().IsGenericType) { continue; } var identifier = _applicationResources.Identify(type); var identifierAsString = _applicationResourceIdentifierConverter.AsString(identifier); var name = ((string)identifier.Resource.Name).ToCamelCase(); currentNamespace.Content.Assign(name) .WithType(t => t.WithSuper("doLittle.commands.Command") .Function .Body .Variant("self", v => v.WithThis()) .Property("_commandType", p => p.WithString(identifierAsString)) .WithObservablePropertiesFrom(type, excludePropertiesFrom: typeof(ICommand), observableVisitor: (propertyName, observable) => { foreach (var commandPropertyExtender in _commandPropertyExtenders) { commandPropertyExtender.Extend(type, propertyName, observable); } })); } if (currentNamespace != globalCommands) { result.Append(_codeGenerator.GenerateFrom(currentNamespace)); } } result.Append(_codeGenerator.GenerateFrom(globalCommands)); return(result.ToString()); }
public ReadModule(IImplementationsOf <IReadModel> readModels, ITypeFinder typeFinder) { _readModels = readModels; var customClassMapTypes = typeFinder.FindMultiple(typeof(IBsonClassMapForReadModel <>)); var readModelHasCustomClassMap = GetHasCustomClassMapDictionary(customClassMapTypes.ToList()); RegisterBsonClassMaps(readModelHasCustomClassMap); }
/// <summary> /// Initializes an instance of <see cref="QueryValidationDescriptors"/> /// </summary> public QueryValidationDescriptors(ITypeFinder typeFinder, IContainer container) { var descriptors = typeFinder.FindMultiple(typeof(QueryValidationDescriptorFor <>)).Where(d => d != typeof(QueryValidationDescriptorFor <>)); descriptors.ForEach(d => { var queryType = d.GetTypeInfo().BaseType.GetTypeInfo().GetGenericArguments()[0]; var descriptor = container.Get(d) as IQueryValidationDescriptor; _descriptors[queryType] = descriptor; }); }
void DiscoverQueryTypesPerTargetType() { var queryTypes = _typeFinder.FindMultiple(typeof(IQueryProviderFor <>)); _queryProviderTypesPerTargetType = queryTypes.Select(t => new { TargetType = GetQueryTypeFrom(t), QueryProviderType = t }).ToDictionary(t => t.TargetType, t => t.QueryProviderType); }
public string Generate() { var typesByNamespace = _typeFinder.FindMultiple <IReadModel>().GroupBy(t => t.Namespace); var result = new StringBuilder(); Namespace currentNamespace; Namespace globalRead = _codeGenerator.Namespace(Namespaces.READ); foreach (var @namespace in typesByNamespace) { if (_configuration.NamespaceMapper.CanResolveToClient(@namespace.Key)) { currentNamespace = _codeGenerator.Namespace(_configuration.NamespaceMapper.GetClientNamespaceFrom(@namespace.Key)); } else { currentNamespace = globalRead; } foreach (var type in @namespace) { var name = type.Name.ToCamelCase(); currentNamespace.Content.Assign(name) .WithType(t => t.WithSuper("doLittle.read.ReadModel") .Function .Body .Variant("self", v => v.WithThis()) .Property("_generatedFrom", p => p.WithString(type.FullName)) .WithPropertiesFrom(type, typeof(IReadModel))); currentNamespace.Content.Assign("readModelOf" + name.ToPascalCase()) .WithType(t => t.WithSuper("doLittle.read.ReadModelOf") .Function .Body .Variant("self", v => v.WithThis()) .Property("_name", p => p.WithString(name)) .Property("_generatedFrom", p => p.WithString(type.FullName)) .Property("_readModelType", p => p.WithLiteral(currentNamespace.Name + "." + name)) .WithReadModelConvenienceFunctions(type)); } if (currentNamespace != globalRead) { result.Append(_codeGenerator.GenerateFrom(currentNamespace)); } } result.Append(_codeGenerator.GenerateFrom(globalRead)); return(result.ToString()); }
#pragma warning disable 1591 // Xml Comments public void SpecifyUsingSpecifiersFrom(Assembly assembly) { _typeFinder .FindMultiple <ICanSpecifyAssemblies>(_contractToImplementorsMap) .Where(t => t.GetTypeInfo().Assembly.FullName == assembly.FullName) .Where(type => type.HasDefaultConstructor()) .ForEach(type => { var specifier = Activator.CreateInstance(type) as ICanSpecifyAssemblies; specifier.Specify(_assemblyRuleBuilder); }); }
/// <inheritdoc/> public void ValidateAll() { var ruleTypes = _typeFinder.FindMultiple(typeof(ITypeRuleFor <>)); foreach (var ruleType in ruleTypes) { var rule = (dynamic)_container.Get(ruleType); var typeForRule = ruleType.GetTypeInfo().GetInterface(typeof(ITypeRuleFor <>).Name).GetTypeInfo().GetGenericArguments()[0]; var types = _typeFinder.FindMultiple(typeForRule); foreach (var type in types) { var problems = _problemsFactory.Create(); rule.Validate(type, problems); if (problems.Any) { _problemsReporter.Report(problems); } } } }
/// <inheritdoc/> public void Provide(IBindingProviderBuilder builder) { builder.Bind <ICanProvideResourceConfigurationsByTenant>().To <ResourceConfigurationsByTenantProvider>(); var resourceConfiguration = new ResourceConfiguration(_typeFinder, _container, _logger); builder.Bind <IResourceConfiguration>().To(resourceConfiguration); var resourceTypeTypes = _typeFinder.FindMultiple <IAmAResourceType>(); var resourceTypeServices = resourceTypeTypes.Select(_ => _container.Get(_) as IAmAResourceType).SelectMany(_ => _.Services); resourceTypeServices.ForEach(_ => builder.Bind(_).To(() => resourceConfiguration.GetImplementationFor(_))); }
/// <summary> /// Initializes a new instance of the <see cref="ResourceConfiguration"/> class. /// </summary> /// <param name="typeFinder"><see cref="ITypeFinder"/> used for discovering types by the resource system.</param> /// <param name="container"><see cref="IContainer"/> to use for getting instances.</param> /// <param name="logger"><see cref="ILogger"/> for logging.</param> public ResourceConfiguration(ITypeFinder typeFinder, IContainer container, ILogger logger) { logger.Information("ResourceConfiguration() - ctor"); _typeFinder = typeFinder; var resourceTypeRepresentationTypes = _typeFinder.FindMultiple <IRepresentAResourceType>(); resourceTypeRepresentationTypes.ForEach(_ => logger.Information($"Discovered resource type representation : '{_.AssemblyQualifiedName}'")); _resourceTypeRepresentations = resourceTypeRepresentationTypes.Select(_ => container.Get(_) as IRepresentAResourceType); ThrowIfMultipleResourcesWithSameTypeAndImplementation(_resourceTypeRepresentations); _logger = logger; }
/// <inheritdoc/> public IBindingCollection DiscoverAndSetupBindings() { _logger.Trace("Discover and setup bindings"); var bindingCollections = new ConcurrentBag <IBindingCollection>(); var allTypes = _typeFinder.All; _logger.Trace("Find all binding conventions"); var conventionTypes = _typeFinder.FindMultiple <IBindingConvention>(); _scheduler.PerformForEach(conventionTypes, conventionType => HandleConvention(conventionType, allTypes, bindingCollections)); return(new BindingCollection(bindingCollections.ToArray())); }
static void AddMvcOptions(IServiceCollection services, ITypeFinder typeFinder) { var mvcOptionsAugmenters = typeFinder.FindMultiple <ICanAddMvcOptions>(); mvcOptionsAugmenters.ForEach(augmenterType => { if (!augmenterType.HasDefaultConstructor()) { throw new ArgumentException($"Type '{augmenterType.AssemblyQualifiedName}' is missing a default constructor"); } var augmenter = Activator.CreateInstance(augmenterType) as ICanAddMvcOptions; services.Configure <MvcOptions>(augmenter.Add); }); }
/// <summary> /// Initializes a new instance of the <see cref="ConfigurationObjectProviders"/> class. /// </summary> /// <param name="typeFinder"><see cref="ITypeFinder"/> to use for finding providers.</param> /// <param name="container"><see cerf="IContainer"/> used to get instances.</param> /// <param name="logger"><see cref="ILogger"/> for logging.</param> public ConfigurationObjectProviders( ITypeFinder typeFinder, IContainer container, ILogger logger) { _typeFinder = typeFinder; _container = container; _logger = logger; _providers = _typeFinder.FindMultiple <ICanProvideConfigurationObjects>() .Select(_ => { _logger.Trace($"Configuration Object provider : {_.AssemblyQualifiedName}"); return(_container.Get(_) as ICanProvideConfigurationObjects); }).ToArray(); }
#pragma warning restore 1591 // Xml Comments void Populate() { var validatorTypes = _typeFinder.FindMultiple(typeof(IValidator)).Where( t => !t.HasInterface <ICommandInputValidator>() && !t.HasInterface <ICommandBusinessValidator>()); foreach (var validatorType in validatorTypes) { var genericArguments = validatorType.GetTypeInfo().BaseType.GetTypeInfo().GetGenericArguments(); if (genericArguments.Length == 1) { var targetType = genericArguments[0]; _validatorsByType[targetType] = validatorType; } } }
/// <inheritdoc/> public void Provide(IBindingProviderBuilder builder) { var interfaceType = typeof(IRuleImplementationFor <>); var ruleImplementations = _typeFinder.FindMultiple(interfaceType); ruleImplementations.ForEach(_ => { var @interface = _.GetInterfaces().SingleOrDefault(t => $"{t.Namespace}.{t.Name}" == $"{interfaceType.Namespace}.{interfaceType.Name}"); var ruleType = @interface.GetGenericArguments()[0]; builder.Bind(ruleType).To(() => { var ruleImplementation = _getContainer().Get(_); var ruleProperty = _.GetProperty("Rule", BindingFlags.Public | BindingFlags.Instance); return(ruleProperty.GetValue(ruleImplementation)); }); }); }
public string Generate() { var typesByNamespace = _typeFinder.FindMultiple(typeof(IQueryFor <>)).GroupBy(t => t.Namespace); var result = new StringBuilder(); Namespace currentNamespace; Namespace globalRead = _codeGenerator.Namespace(Namespaces.READ); foreach (var @namespace in typesByNamespace) { if (_configuration.NamespaceMapper.CanResolveToClient(@namespace.Key)) { currentNamespace = _codeGenerator.Namespace(_configuration.NamespaceMapper.GetClientNamespaceFrom(@namespace.Key)); } else { currentNamespace = globalRead; } foreach (var type in @namespace) { var name = type.Name.ToCamelCase(); var queryForTypeName = type.GetTypeInfo().GetInterface(typeof(IQueryFor <>).Name).GetGenericArguments()[0].Name.ToCamelCase(); currentNamespace.Content.Assign(name) .WithType(t => t.WithSuper("doLittle.read.Query") .Function .Body .Variant("self", v => v.WithThis()) .Property("_name", p => p.WithString(name)) .Property("_generatedFrom", p => p.WithString(type.FullName)) .Property("_readModel", p => p.WithLiteral(currentNamespace.Name + "." + queryForTypeName)) .WithObservablePropertiesFrom(type, excludePropertiesFrom: typeof(IQueryFor <>), propertyVisitor: (p) => p.Name != "Query")); } if (currentNamespace != globalRead) { result.Append(_codeGenerator.GenerateFrom(currentNamespace)); } } result.Append(_codeGenerator.GenerateFrom(globalRead)); return(result.ToString()); }