2013-07-15 90 views
1

对于我的应用程序,我试图编写一个配置控制器来加载和保存某些模块的设置。为此,我将使用INI文件,其中段名称将表示模块名称(或其他标识)以及由键表示的值。获取模块名称或标识

我在自举程序中注册了我的控制器,并在适当的类中使用我的构造函数中的接口进行注入。不过,我不想每次需要获取或设置一个值时输入模块名称,所以我尝试使用调用者信息来找出哪个模块(或类)正在调用该方法,但这显然不起作用(返回空字符串)。

是否有另一种方法来实现我想要做的?

引导程序:

protected override void ConfigureContainer() 
    { 
     base.ConfigureContainer(); 

     Container.RegisterType<IConfig, ConfigController>(new ContainerControlledLifetimeManager()); 
    } 

配置接口:

public interface IConfig 
{ 
    string[] GetSettings(string caller = ""); 

    void Set<T>(string setting, T value, string caller = "") where T : class; 
    T Get<T>(string setting, string caller = "") where T : class; 
} 

回答

1

使用呼叫者说法是容易出错。您有许多选项可以避免它:

  1. 为每个模块注册一个ConfigController。 Unity支持多个命名注册。您可以在每个模块中注入合适的控制器模块初始化,或用Dependency属性:

     Container.Register<IConfig, ConfigController>("module1", 
          new InjectionConstructor("module1")) 
           .Register<IConfig, ConfigController>("module2", 
          new InjectionConstructor("module2")); 
    
         class Module1 { 
          public Module1([Dependency("module1")] IConfig config) {... } 
         } 
    
  2. 定义和实现,它返回一个配置IConfig实施IConfigFactory。

    interface IConfigFactory { 
         IConfig Create(String moduleName); 
        } 
    
  3. ConfigController可以识别模块detecting the method the made the call

+0

我决定使用第一个建议,它的作品就像一个魅力!仍试图找到一种方法来注册控制器在boostrapper中,而不是在模块本身,但似乎无法得到在初始化之前在DirectoryModuleCatalog中的模块。无论如何非常感谢,这绝对让我回到正轨:) – Kryptoxx