コード例 #1
0
        private void ParseMiddlewares(IMessagePipeline pipeline, XmlNodeList nodes)
        {
            foreach (XmlNode node in nodes)
            {
                var parameters = new Dictionary <string, string>();
                if (node.NodeType != XmlNodeType.Element)
                {
                    continue;
                }
                if (node.Attributes == null)
                {
                    throw new MessagesConfigurationException("Middleware tag does not have attributes.");
                }
                foreach (XmlAttribute attr in node.Attributes)
                {
                    parameters.Add(attr.Name, attr.Value);
                }

                var typeName = node.Attributes["type"].Value;
                if (string.IsNullOrWhiteSpace(typeName))
                {
                    throw new MessagesConfigurationException("Middleware tag does not have \"type\" attribute.");
                }

                var type = Type.GetType(typeName);
                if (type == null)
                {
                    throw new MessagesConfigurationException($"Cannot load type {typeName}.");
                }

                var ctor = type.GetConstructors().FirstOrDefault(c => c.GetParameters().Length == 1 &&
                                                                 c.GetParameters()[0].ParameterType == typeof(IDictionary <string, string>));
                if (ctor == null)
                {
                    ctor = type.GetConstructors().FirstOrDefault(c => c.GetParameters().Length == 0);
                }

                if (ctor == null)
                {
                    var msg = "Cannot find public parameterless constructor or constructor that accepts IDictionary<string, string>.";
                    throw new MessagesConfigurationException(msg);
                }

                var middleware = ctor.GetParameters().Length == 1
                    ? ctor.Invoke(new object[] { parameters }) as IMessagePipelineMiddleware
                    : ctor.Invoke(new object[] { }) as IMessagePipelineMiddleware;
                if (middleware == null)
                {
                    throw new MessagesConfigurationException($"Cannot instaniate pipeline middleware {type.Name}.");
                }

                SetIdProperty(middleware, node);

                pipeline.AddMiddlewares(middleware);
            }
        }