如何在 Azure 移动应用程序的 SignalR.Hub 中获取 MobileAppSettingsDictionary

How to get MobileAppSettingsDictionary in SignalR.Hub in Azure Mobile Apps

我正在从 Azure 移动服务迁移(准确地说是升级)到 Azure 移动应用程序。我的 Azure 后端 (.net) 曾经在 SignalR 和通知中心提供混合聊天实现。

以下代码片段在 Azure 移动服务 环境

中工作
[HubName("chatHub")]
public class ChatHub : Hub
{
    public ApiServices Services { get; set; }
    public IServiceTokenHandler handler { get; set; }
    protected async Task NotifyParticipants(IPushMessage message, String tag)
    {
        await Services.Push.SendAsync(message, tag);
    }
}

但是由于 ApiServicesAzure Mobile Apps 环境中不再可用,我应该如何重构实现?

我在发送通知的 API 控制器中使用了以下代码片段,但我无法在上面的 chatHub 中使用相同的代码片段,因为我无法获取 HttpConfiguration 需要检索我的通知中心设置。

[MobileAppController]
public class SomeController : ApiController
{
    protected NotificationHubClient hubClient { get; set; }
    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);

        // Get the settings for the server project.
        HttpConfiguration config = this.Configuration;
        MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();

        // Get the Notification Hubs credentials for the Mobile App.
        string notificationHubName = settings.NotificationHubName;
        string notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;

        // Create a new Notification Hub client.
        hubClient = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    }
    protected async Task NotifyParticipants(IPushMessage message, String tag)
    {
        await hubClient.SendGcmNativeNotificationAsync(message.ToString(), tag);
    }
}

如果您需要访问 NH 连接字符串(或任何其他设置),您始终可以直接使用 ConfigurationManager,例如:

var connstr = ConfigurationManager
    .ConnectionStrings[MobileAppSettingsKeys.NotificationHubConnectionString]
    .ConnectionString;

如果您想访问实际的 MobileAppSettingsDictionary(例如,模拟测试会更容易),您可以将 DependencyResolver 连接到 SignalR:http://www.asp.net/signalr/overview/advanced/dependency-injection .

我使用了他们的 Ninject 示例(但他们 link 用于其他提供商)并且我在 Startup.MobileApp.cs 中的代码如下所示:

var kernel = new StandardKernel();
var resolver = new NinjectSignalRDependencyResolver(kernel);
kernel.Bind<MobileAppSettingsDictionary>()
    .ToConstant(config.GetMobileAppSettingsProvider().GetMobileAppSettings());

var signalRConfig = new HubConfiguration();
signalRConfig.Resolver = resolver;
app.MapSignalR(signalRConfig);

然后在你的 Hub 中你做这样的事情(你也可以使用构造函数注入):

[Inject]
public MobileAppSettingsDictionary MobileAppSettings { get; set; }

那么您应该可以访问该集线器中任何位置的设置。