的.config来构造名堂?

问题描述:

我工作的一个快速的项目,以监测/处理数据。本质上,这只是监视器,时间表和处理器。监视器检查用于使用日程数据(FTP,本地,IMAP,POP等),并发送新的数据的处理器。他们都有接口。的.config来构造名堂?

我试图找到使用配置来配置每个显示器采用什么时间表/处理器理智的方式。这很容易:

<monitor type="any.class.implementing.monitor"> 
    <schedule type="any.class.implementing.schedule"> 
     ... 
    </schedule> 
    <processor type="any.class.implementing.processor" /> 
</monitor> 

我在努力什么是什么是配置任何老监视器/时间表/处理器投入混合的最佳方式是什么。一方面,一个可以实现构造PARAMS或性质(给OT采取任何语法):

<monitor type="any.class.implementing.monitor"> 
    <args> 
     <arg value="..." /> 
    </args> 
    <properties> 
     <property name="..." value=..." /> 
    </properties> 
    <schedule type="any.class.implementing.schedule"> 
     ... 
    </schedule> 
    <processor type="any.class.implementing.processor" /> 
</monitor> 

另一个解决方案是在每个取自定义配置为PARAM接口工厂方法:

public IMonitor Create(CustomConfigSection config); 

我看到有人使用两者。你喜欢哪个?贸易的任何窍门映射配置来构造什么时候?

我对DI是否适合这个烂摊子有些t t。最终,这将是一个集每个监视器实例绑定的,这似乎除了默认值,配置可以覆盖毫无意义的。

当我完成这样的事情时,我实现了一个基本上作为工厂来解析配置,创建在配置中指定的类型的对象,并返回它们在某种数据结构中的IConfigurationSectionHandler (通常是一个List或Dictionary)。无论您使用的是否是IConfigurationSectionHandler,我都认为工厂是一条路,因为您将本地化处理解析配置文件和创建一个类(或每个部分一个)的对象的代码。

我还喜欢使用具有简单构造函数和属性setter/getters的类来配置具有构造函数中大量参数的类。这使工厂更容易操作,并减少工厂与正在建造的班级之间的耦合。

首先,我定义表示监视器配置元素:

public class MonitorElement : ConfigurationElement 
{ 
    // ...whatever schema you prefer... 
} 

public class MonitorElementCollection : ConfigurationElementCollection 
{ 
    // ...standard implementation... 
} 

以及配置部来承载它们:

public class YourSection : ConfigurationSection 
{ 
    [ConfigurationProperty("monitors")] 
    [ConfigurationCollection(typeof(MonitorElementCollection))] 
    public MonitorElementCollection Monitors 
    { 
     get { return (MonitorElementCollection) this["monitors"]; } 
    } 
} 

然后,我将定义表示所设置的显示器的接口:

public interface IMonitorRepository 
{ 
    IEnumerable<Monitor> GetMonitors(); 
} 

然后创建一个读取配置文件的实现E:

public sealed class ConfiguredMonitorRepository : IMonitorRepository 
{ 
    private readonly string _sectionName; 

    public ConfiguredMonitorRepository(string sectionName) 
    { 
     _sectionName = sectionName; 
    } 

    public IEnumerable<Monitor> GetMonitors() 
    { 
     var section = (YourSection) ConfigurationManager.GetSection(_sectionName); 

     if(section != null) 
     { 
      foreach(var monitor in section.Monitors) 
      { 
       yield return ...create and configure monitor... 
      } 
     } 
    } 
} 

这定义了你把配置到实际情况,这是只有一半你的问题。我认为用于设置构造函数参数和属性的XML语法很好。您可以从Autofac's XML configuration system收集一些API和实施建议。

真的,你正在做的是一个IoC容器的长处;你可以考虑利用其中之一。