【问题标题】:How to reconfigure SQLTransport based NServicebus in Asp.net Web API?如何在 Asp.net Web API 中重新配置基于 SQLTransport 的 NServicebus?
【发布时间】:2014-09-30 15:44:16
【问题描述】:

我在我的 ASP.net Web api 项目中使用 NServicebus(版本 4.6.3)和 SQLTransport。对于不同环境(Dev、QA 等)的队列,我有不同的连接字符串。我的配置如下:

public class BusConfigurator
{
    public static IStartableBus Bus { get; private set; }

    public static void DisposeBus()
    {
        if (Bus == null) 
            return;

        Bus.Shutdown();
        Bus.Dispose();
        Bus = null;
    }
    public static void InitializeServiceBus(string connectionString)
    {

        var configure = Configure.With()
            .DefineEndpointName("MyEndPoint")
            .Log4Net(new DebugAppender { Threshold = Level.Warn })
            .UseTransport<SqlServer>(connectionString)
            .PurgeOnStartup(false)
            .SetDefaultTransactionLevel()
            .UnicastBus(); // Error is thrown here on second call

        configure.MyCustomSQLServerPersistence();            

        Bus = configure.CreateBus();


    }

    public static void StartBus()
    {
        Bus.Start(() => Configure.Instance.ForInstallationOn<NServiceBus.Installation.Environments.Windows>().Install());
    }

} 

我在应用中有一个下拉菜单,以便用户可以选择环境。根据选择,我想重新配置总线。因此,我调用 DisposeBus,然后将连接字符串传递给 IntializeServiceBus 方法,然后是 startBus。它第一次工作,但在使用不同的连接字符串再次调用时会在下面抛出错误:

无法设置键值:NServiceBus.Transport.ConnectionString。设置已被锁定以进行修改。请在配置管道中更早地移动任何配置代码 源=NServiceBus.Core 线=0 BareMessage=无法设置键值:NServiceBus.Transport.ConnectionString。设置已被锁定以进行修改。请在配置管道中移动任何配置代码

NServicebus 是否打算以这种方式使用/配置? (我猜可能不是)如果没有,那么是否有解决方法/不同的方法?

【问题讨论】:

  • Id' 说在 NServiceBus v4.x 中,除了回收 Web 应用程序之外,没有办法使配置无效/重新创建,还不知道(我正在设置一个示例)如果在 v5 中有什么可以实现的

标签: c# asp.net asp.net-web-api nservicebus


【解决方案1】:

在 V4 或更低版本中,没有办法通过正常的人类手段来做到这一点。每个 AppDomain 只有一个总线。所有的配置 API 都是静态的,所以如果你尝试一下,你就会遇到遇到的问题。

通过“人为手段”,我的意思是可以通过在您的进程中启动一个新的 AppDomain,在其中设置一个总线,然后在完成后将其拆除来做一些疯狂的事情。这可能是可能的。我没试过。我不会推荐它。

在 V5 中,配置 API 完全重新设计,不是静态的,因此这是可能的:

var cfg = new BusConfiguration();

// Set up all the settings with the new V5 Configuration API

using (var justOneBus = NServiceBus.Bus.Create(cfg).Start())
{
    // Use justOneBus, then it gets disposed when done.
}

没错。它是一次性的。然后你可以再做一次。在您的情况下,您不希望将其放在 using 块中 - 您希望将其设置在某处,当下拉列表切换时,在当前实例上调用 Dispose 并使用新参数重建它。

但是请记住,创建 Bus 的成本仍然很高。它绝对仍然是您希望将其视为应用程序范围的单例(或类似单例)的实例。您绝对不想为每个 Web 请求单独启动一个。

【讨论】:

  • +1 不错的答案!谢谢你。我决定更改应用程序的设计,这样我就不必依赖重新创建总线了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多