Delen via


Enterprise Library Configuration Best Practices

 

There is no doubt, we (as Microsoft Consutants) must use entlib for instrumentation purposes, like logging and exception handling.

I must to admit that there are some design decisions I don’t like too much, like the high number of assemblies or the verbose configuration mechanism, but this is another story.

So if have decided to use it, like some product teams have started to do (eg Exchange 2010), here are some tips to maintain your config files as clean as possible.

Tip n1. Avoid to store all of your config settings in your primary config file (app.config or web.config).

Instead you can use the configuration block to redirect the configuration to an external file, so you can reuse the same settings without copy/paste the whole xml.

Once you have set the new file, you can set the file properties in VS to force copy to output dir on each build.

Tip n2. Use the new fluent interface to indicate the entilib config file (only in EntLib 5.0 and above)

To indicate the name of your new file, while avoiding the standard configuration mechanism:

<configuration>
    <configSections>
        <section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <enterpriseLibrary.ConfigurationSource selectedSource="System Configuration Source"
        parentSource="">
        <sources>
            <add name="EntLibConfig" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                filePath="entlib.config" />
            <add name="System Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        </sources>
        <redirectSections>
            <add sourceName="EntLibConfig" name="loggingConfiguration" />
            <add sourceName="EntLibConfig" name="exceptionHandling" />
            <add sourceName="EntLibConfig" name="instrumentationConfiguration" />
        </redirectSections>
    </enterpriseLibrary.ConfigurationSource>
</configuration>

You can use the fluent interface like this:

var builder = new ConfigurationSourceBuilder();
var configSource = new FileConfigurationSource("entlib.config");
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);