Search code examples
c#dependency-injectionunity-containerenterprise-libraryenterprise-library-5

Programatically update a configuration within a container


In my app I ask the user which database they want to connect to and I was writing it back into EL5.0 like this:

    var builder = new ConfigurationSourceBuilder();

    builder.ConfigureData()
           .ForDatabaseNamed("UserDatabase")
             .ThatIs.ASqlDatabase()
             .WithConnectionString(sqlConnectionStringBuilder.ConnectionString)
             .AsDefault();

    var configSource = new DictionaryConfigurationSource();
    builder.UpdateConfigurationWithReplace(configSource);
    EnterpriseLibraryContainer.Current
        = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

Which was then used whenever I called GetInstance like this:

    TestSQLConnection testSQLConnection = 
        EnterpriseLibraryContainer.Current.GetInstance<TestSQLConnection>();

Now I'm trying to use Unity in my programs main class

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        IUnityContainer unityContainer = new UnityContainer().AddNewExtension<EnterpriseLibraryCoreExtension>();
        Application.Run(unityContainer.Resolve<MainForm>());
    }

and I use unityContainer which is a one of MainForm's dependencies instead of GetInstance():

    TestSQLConnection testSQLConnection = unityContainer.Resolve<TestSQLConnection>(); 

But this doesn't use the updated configuration.

How do I merge the updated configuration in Unity like I did with the EL static class?


Solution

  • In addition to Phil's answer (which I second), containers should always be used according to the Register Resolve Release pattern. This implies that once you start Resolving (and Releasing) instances from the container, you should not modify its configuration. I can't really tell from the question whether that's what is being asked for, but the title seems to imply it.