开发者

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 con开发者_开发百科figuration in Unity like I did with the EL static class?


How is unityContainer getting passed into MainForm? It looks like you are resolving one container with another, since you resolve MainForm like this, after creating a new UnityContainer:

Application.Run(unityContainer.Resolve<MainForm>());

. . . and then you say unityContainer is a dependency of MainForm.

It looks to me like you have at least two, and possibly three different instances of the container. Can you simply use EnterpriseLibraryContainer.Current in all cases?

As an aside, in most cases you don't want to pass the container into your implementations or call Resolve() directly from your implementations. This is the Service Locator Anti-Pattern.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜