注入应用程序配置的最佳方式 [英] Best way of injecting application configuration

查看:117
本文介绍了注入应用程序配置的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我正在为这个梦幻般的网站做一个关于正确的方式注入配置设置到应用程序组件的问题。所以,概述是:我有一个应用程序用C#.Net 3.5编写。它由3个程序集组成 - 一个核心,一个数据和一个服务。数据&服务程序集需要通过设置文件(例如

Well, I'm making my foray into this fantastic site with a question about the correct way to inject configuration settings into application components. So, the overview is : I have an application written in C# .Net 3.5. It consists of 3 assemblies - a Core, a Data and a Service. The data & service assemblies require settings retrieved from the app.config, which is done via a settings file, eg.

)从app.config中检索的设置。代码:

Code :

public static String RequestQueueConnectionString
{
    get { return ConnectionSettings.Default.RequestQueueConnectionString; }
}

配置:

<applicationSettings>
  <MyNamespace.Data.ConnectionSettings>
    <setting name="RequestQueueConnectionString" serializeAs="String">
    ...



现在,所有程序集都使用StructureMap为IoC设置 - 我的思想应该提供我正在寻找的答案,但我只是不能完全看到它!

Now, the assemblies are all setup using StructureMap for IoC - which to my mind should provide the answer to what I am looking for, but I just can't quite see it!

IoC:

public static void ConfigureStructureMap(IContainer container)
{
    container.Configure(x => ...
    ...

我想要做的是注入一个已经填充到IoC容器中的配置类,这些设置用于该程序集,而不是设置文件/ app.config中指定的那些设置。

What I want to be able to do is to inject a configuration class already populated into the IoC container such that those settings are used for that assembly, NOT those specified in the settings file / app.config. So perhaps :

public static void ConfigureStructureMap(IContainer container, MyConfigClass config)
{
    container.Configure(x => x.For<DataConfig>()
                              .Singleton()
                              .Use ???
    ...

我希望我在这里提供了足够的细节 - 如果我没有,请原谅一个新手,请让我知道在回答这个问题有什么帮助吗?

I hope I have provided enough details here - forgive a newbie if I have not and please let me know what else would be helpful in answering this!

推荐答案

所以,经过大量的搜索和尝试和错误,我被提出了@ default.kramer的链接,我一直追随!有一点点试验和错误,再次(在我看来最好的方式),我设法得到我寻找的解决方案。现在,虽然你可以跟随链接(我强烈建议这样做),我将post的解决方案我的问题,因为我实现它。希望这可能会帮助有类似问题的人。

So, after a lot of searching and trial and error, I was presented with @default.kramer's link, which I duely followed! With a little bit of trial and error, again (best way in my opinion), I managed to get the solution I was looking for. Now, whilst you can follow the link (and I would highly suggest doing so), I am going to post the solution to my question as I implemented it. Hopefully this might help someone with a similar problem.

所以,现在我的配置设置类如下:

So, I now have my configuration setup class like so :

public static class DispatchConfiguration
{
    public static void ConfigureStructureMap(IContainer container, IDispatchConfiguration dispatchConfig)
    {
        DispatchProcessBatchSize = dispatchConfig.DispatchProcessBatchSize;
        ServiceIsActive = dispatchConfig.ServiceIsActive;
        ...
    }

现在,在使用设置文件以从app.config文件中检索配置。这显然是很好地确保我有灵活性,在更改我的配置设置,但它留给我的问题,无法轻松测试这些设置。说9-10测试需要服务是活跃的,但1测试想测试ServiceIsActive = false;,现在我有麻烦。

Now, before I was using a settings file to retrieve the configuration out of the app.config file. This was obviously good for ensuring I had flexibility in changing my config settings, but it left me with the problem of not being able to easily test those settings. Say 9/10 tests required the service to be active, but 1 test wanted to test "ServiceIsActive = false;", now I'm in trouble.

现在,我可以通过测试注入配置:

Now, however, I am able to inject the configuration from the test :

[Given(@"Config\.IsServiceActive returns false")]
public void GivenConfig_IsServiceActiveReturnsFalse()
{
    var settings = new DispatchSettings
    {
        ServiceIsActive = false,
        DispatchProcessBatchSize = 100,
        UpdatedBy = "Unit Test"    
    };

    DispatchConfiguration.ConfigureStructureMap(ObjectFactory.Container, settings);
}

然后在现实世界中,我可以从应用程序获取设置。 config:

And then in the real world I am able to get the settings from app.config :

public void Start(String[] args)
{
    var dispatchConfig = this.GetDispatchConfiguration();
    DispatchConfiguration.ConfigureStructureMap(ObjectFactory.Container, dispatchConfig);
    ...
}

private IDispatchConfiguration GetDispatchConfiguration()
{
    var config = (DispatchSettings)ConfigurationManager.GetSection("DispatchSettings");
    return config;
}

然后实际的配置类如下:

And then the actual config class looks like :

[XmlRoot(ElementName = "DispatchSettings", Namespace = "")]
public sealed class DispatchSettings : IDispatchConfiguration
{
    public Int32 DispatchProcessBatchSize { get; set; }
    public Boolean ServiceIsActive { get; set; }
    ...
}

为了完整起见,像这样:

For the sake of completeness the interface looks like so :

public interface IDispatchConfiguration
{
    Int32 DispatchProcessBatchSize { get; }
    Boolean ServiceIsActive { get; }
    ...
}

最后,配置文件看起来像this:

And finally, the config file looks like this :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="DispatchSettings" type="MyNamespace.XmlConfigurator, MyNamespace.Core" />
    </configSections>

    <DispatchSettings type="MyNamespace.DispatchSettings, MyNamespace.Core">
        <ServiceIsActive>True</ServiceIsActive>
        <DispatchProcessBatchSize>100</DispatchProcessBatchSize>
    </DispatchSettings>

eye会发现MyNamespace.XmlConfigurator。我在我的一个Google旅程中发现了这个,并且代码允许你反序列化一个Xml配置到你想要的类中(如这个例子所示)。所以,为了确保你有完整的代码,使这项技术工作,下面是XmlConfigurator的代码。我不记得我在哪里碰到它了,但是非常感谢编写它的人。

Now, anyone with a keen eye will spot "MyNamespace.XmlConfigurator". I found this on one of my Google journeys, and the code allows you to deserialize an Xml config into a class of your desire (as shown in this example). So, to ensure you have the complete code to make this technique work, below is the code for the XmlConfigurator. I cannot remember where I came across it, but a big thanks to the person who wrote it!!

public sealed class XmlConfigurator : IConfigurationSectionHandler
{
    public XmlConfigurator()
    {
    }

    public object Create(object parent, object configContext, XmlNode section)
    {
        XPathNavigator navigator = null;
        String typeName = null;
        Type sectionType = null;
        XmlSerializer xs = null;
        XmlNodeReader reader = null;

        try
        {
            Object settings = null;

            if (section == null)
            {
                return settings;
            }

            navigator = section.CreateNavigator();
            typeName = (string)navigator.Evaluate("string(@type)");
            sectionType = Type.GetType(typeName);
            xs = new XmlSerializer(sectionType);
            reader = new XmlNodeReader(section);

            settings = xs.Deserialize(reader);

            return settings;
        }
        finally
        {
            xs = null;
        }
    }
}

我希望这允许任何具有类似问题的人解决它,并且足够清楚跟随!

And there you have it! I hope this allows anyone with a similiar issue to resolve it and is clear enough to follow!

这篇关于注入应用程序配置的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆