Jus*_*n_H 4 castle-windsor castle inversion-of-control
嗨,我是温莎城堡的新手,正在努力理解一些基础知识,所以我想我发布一个问题而不是通过代码来希望尽快解决我的问题。
我有一个需要从配置文件 web.config 中提取信息的网络服务。此信息位于自定义配置部分中,我想知道如何将该信息提供给需要它的类。我不想将该类绑定到配置文件,因为我可能会通过 IIS 或自定义 Windows 服务托管它。我的第一次尝试是做这样的事情:
iocCon.Register(Component.For<ErrorMessagesSection>().LifeStyle.Singleton.Instance(FindConfigSection<ErrorMessagesSection>())); 
private T FindConfigSection<T>() where T : ConfigurationSection
    {
        System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/web.config");//TODO: remove this hard coding to iis hosting  .OpenExeConfiguration(ConfigurationUserLevel.None);
        ConfigurationSectionGroupCollection sectionGroups = config.SectionGroups;
        foreach (ConfigurationSectionGroup sectionGroup in sectionGroups)
            foreach (ConfigurationSection configurationSection in sectionGroup.Sections)
                if (configurationSection.GetType() == typeof(T))
                    return (T) configurationSection;
        return null;
    }
该部分只能定义一次,因此这基本上是获取该部分,以便将其注入到错误消息工厂类的构造函数中。这不会引发任何错误,但是我注意到该部分被创建了两次,这导致了其他问题(我应该修复但......)无论如何为了解决这个问题我决定我会创建单个实例并自己注册它所以我试过:
UGLY_HACK = new ConfigFileErrorMessageManager(eMessages);
iocContationer.Register(Component.For<IErrorMessageManager>().ImplementedBy<ConfigFileErrorMessageManager>().LifeStyle.Singleton.Instance(UGLY_HACK));
这是一个刚刚创建的容器的第一次注册,它会爆炸:
[ComponentRegistrationException: This component has already been assigned implementation xxx.ConfigFileErrorMessageManager]
Castle.MicroKernel.Registration.ComponentRegistration`1.ImplementedBy(Type type,     IGenericImplementationMatchingStrategy genericImplementationMatchingStrategy) +310
Castle.MicroKernel.Registration.ComponentRegistration`1.Instance(TService instance) +44
我的第一个问题:这个错误怎么可能(没有其他任何东西被注册)/或者它是否意味着比它看起来更微妙的东西?第二个问题:将配置信息获取到需要它的类的最佳实践是什么(我这样做是不是错了)?
谢谢你的帮助
看起来您真正需要的只是一个适配器,ConfigurationManager它允许您向 Windsor 注册应用程序的配置。
下面是一个IConfigurationManager实现与适配器WebConfigurationManager,它会让你做到这一点。
注册它
container.Register(
    Component.For<IConfigurationManager>()
             .Instance(new WebConfigurationManagerAdapter()));
现在您可以注入IConfigurationManager需要访问配置的组件。
如果您只想注入特定部分,则可以向 Windsor 注册一个工厂方法,以从IConfigurationManager容器中注册的强类型部分中检索强类型部分,例如
container.Register(
    Component.For<ErrorMessagesSection>()
             .UsingFactoryMethod(kernel => 
                 kernel.Resolve<IConfigurationManager>()
                       .GetSection<ErrorMessagesSection>("errorSectionName")));
| 归档时间: | 
 | 
| 查看次数: | 1278 次 | 
| 最近记录: |