在.NET中的各种组件之间共享配置设置

时间:2012-02-08 08:27:10

标签: .net configuration clickonce

我知道关于SO的类似问题很多,但我有一个警告。

基本前提是可预测的:我继承了由几个组件组成的产品,所有这些组件共享一些配置设置,其中包括连接字符串。目前,这些组件调用带有哈希密码的Web服务以检索连接字符串(blegh),但这有时会导致Windows启动时需要配置值的Web服务和NT服务之间的竞争条件。

我想创建一个优雅的解决方案,允许我从单个安全的位置(即registry或machine.config)共享这些设置。在给定单个部署环境的情况下,其中任何一个都可以轻松实现,但(这是问题)其中一个组件是单击一次应用程序。

简而言之,我的问题是:如何为配置设置创建集中式机制,这些机制也将传播到单击一次部署?

我考虑的选项:

据我所知,这两种解决方案都取决于共享配置文件的本地副本的可用性,这不适用于点击一次。

有关click-once应用程序的部署环境需要注意两点:

  • 部署始终位于公司LAN网络中,因此配置设置(如连接字符串)普遍适用。
  • 安装时随点击一次应用程序打包的配置设置可以安全地在后续部署时被覆盖。

1 个答案:

答案 0 :(得分:0)

如评论中所示,我建议当前的解决方案是一种不错的方式,因为Web服务对安全问题不敏感,并且它确保了集中式解决方案。要克服竞争条件,可以使用互斥锁强制客户端等待服务器启动。示例代码:

string mutexName = "C01F6FBB-50E9-4BFA-AFBA-209C316AE9FB";
TimeSpan waitInterval = TimeSpan.FromSeconds(1d);

// Server sample
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
    // similate some startup delay for the server
    Thread.Sleep(TimeSpan.FromSeconds(5));

    using (Mutex mutex = new Mutex(true, mutexName))
    {
        Console.WriteLine("Server: Good morning!");

        // Do server business, ensure that the mutex is kept alive throughout the server lifetime
        // this ensures that the application can always check whether the server is available or not
        Thread.Sleep(TimeSpan.FromSeconds(5));    
    }
});

// Application sample
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
    Console.WriteLine("Application: Checking the server...");

    bool mutexOpened = false;

    while (!mutexOpened)
    {
        try
        {
            using (Mutex mutex = Mutex.OpenExisting(mutexName))
            {
                mutexOpened = true;
            }
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Application: Server is not yet ready....");

            // mutex does not exist yet, wait for the server to boot up
            Thread.Sleep(waitInterval);
        }
    }

    // Server is ready, we can do our application business now
    // note that we dont need to preserve the mutex anymore. 
    // we only used it to ensure that the server is available.
    Console.WriteLine("Application: Good morning to you!");
});

Console.ReadLine();

希望这有帮助!

相关问题