Esempio n. 1
0
        private void AddMethod(MethodInfo method)
        {
            IEnumerable <RegexCommandAttribute> attributes = method.GetCustomAttributes <RegexCommandAttribute>();

            if (!attributes.Any())
            {
                _log.LogWarning("Cannot initialize Regex command from {TypeName}'s method {MethodName} - {Attribute} missing", method.DeclaringType.FullName, method.Name, nameof(RegexCommandAttribute));
                return;
            }
            foreach (RegexCommandAttribute attribute in attributes)
            {
                Commands.Add(RegexCommandInstance.Build(method, attribute, _serviceProvider));
            }
        }
        public object GetModuleInstance(RegexCommandInstance commandInstance)
        {
            // init module info
            RegexCommandModuleInfo moduleInfo;

            if (!_knownModules.TryGetValue(commandInstance, out moduleInfo))
            {
                IEnumerable <ConstructorInfo> constructors = commandInstance.ModuleType
                                                             .GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                                                             .OrderByDescending(ctor => ctor.GetParameters().Length);
                foreach (ConstructorInfo ctor in constructors)
                {
                    moduleInfo = InitializeModuleInfo(ctor);
                    if (moduleInfo != null)
                    {
                        _knownModules.Add(commandInstance, moduleInfo);
                        break;
                    }
                }
                if (moduleInfo == null)
                {
                    throw new InvalidOperationException($"Cannot create {commandInstance.ModuleType.FullName} - none of the constructors can have its dependencies resolved");
                }
            }

            // check if there is already a persistent or shared instance
            if (_persistentInstances.TryGetValue(commandInstance, out object instance))
            {
                return(instance);
            }
            if (_sharedInstances.TryGetValue(moduleInfo.Type, out instance))
            {
                _persistentInstances.Add(commandInstance, instance);
                return(instance);
            }

            // create a new instance, cache it if it's persistent
            instance = moduleInfo.CreateInstance();
            if (moduleInfo.IsPersistent)
            {
                _persistentInstances.Add(commandInstance, instance);
                if (moduleInfo.IsShared)
                {
                    _sharedInstances.Add(moduleInfo.Type, instance);
                }
            }

            return(instance);
        }