按类型或类型字符串强类型的Azure Mobile Service表对象?

时间:2014-08-11 14:56:29

标签: c# azure reflection azure-mobile-services strong-typing

我想在一些应用程序中使用单一的移动服务。我希望他们每个人都使用相同的类(即“日志”),但我希望服务器后端的信息转到一个单独的表。我是从便携式类库中做到的。

一种选择是使用[DataTable(string)]属性;但是,我想让整个事情自动化(即单个DLL包含在项目中,它将自动从上下文构造表名,即string +“Log”)。我找不到修改DataTable属性运行时的方法来获取对强类型表的引用。

我是否还有其他选择,而不是使用弱类型表并自行序列化JSON,还是可以单独根据类型或类型名称创建强类型引用?

1 个答案:

答案 0 :(得分:1)

无法根据运行时中的某些信息更改数据表的名称(此功能存在于Android SDK中,因此您可以考虑将creating a feature request添加到托管中SDK也是。)

然而,你可以做的是使用一个消息处理程序,它可以"调整"与表相关的操作的请求URI,以便您可以以编程方式实现此操作。基本上,除了您希望在多个应用程序之间共享的数据类型之外,您的可移植库还将公开一个从DelegatingHandler扩展的类。以下是此类处理程序的示例。

public class AppSpecificTableNamesHandler : DelegatingHandler
{
    public const string TablePrefix = "MyType";
    private const string TablesPathPrefix = "/tables/";

    private string tableSuffix;
    public AppSpecificTableNamesHandler(string tableSuffix)
    {
        this.tableSuffix = tableSuffix;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        UriBuilder uriBuilder = new UriBuilder(request.RequestUri);
        string path = uriBuilder.Path;
        if (path.StartsWith(TablesPathPrefix + TablePrefix))
        {
            path = TablesPathPrefix + TablePrefix +
                this.tableSuffix + path.Substring(TablesPathPrefix.Length + TablePrefix.Length);
            uriBuilder.Path = path;
            request.RequestUri = uriBuilder.Uri;
        }

        return base.SendAsync(request, cancellationToken);
    }
}

您可以在https://gist.github.com/carlosfigueira/9582c08851d116f5a426找到我用来测试的解决方案的完整代码(至少是最重要的类)。