集中CloudStorageAccount和TableServiceContext实例

本文关键字:实例 TableServiceContext CloudStorageAccount 集中 | 更新日期: 2023-09-27 18:22:09

在ASP.NET MVC 3 Web角色中,我意识到我已经写了很多以下代码:

var account = 
    CloudStorageAccount.Parse(
        RoleEnvironment.GetConfigurationSettingValue("DataConnectionString")
    );
var ctx = 
    account.CreateCloudTableClient().GetDataServiceContext();

因此,我决定将其集中用于整个ASP.NET MVC应用程序,并创建了以下具有静态属性的类:

internal class WindowsAzureStorageContext {
    public static CloudStorageAccount StorageAccount { 
        get {
            return
                CloudStorageAccount.Parse(
                    RoleEnvironment.GetConfigurationSettingValue("DataConnectionString")
                );
        }
    }
    public static TableServiceContext TableServiceCtx { 
        get {
            return
                StorageAccount.CreateCloudTableClient().GetDataServiceContext();
        } 
    }
}

而且,我在我的控制器中使用如下:

public class HomeController : Controller {
    private readonly TableServiceContext ctx = 
        WindowsAzureStorageContext.TableServiceCtx;
    public ViewResult Index() {
        var model = ctx.CreateQuery<TaskEntity>(Constants.TASKS_TABLE).
            Where(x => x.PartitionKey == string.Empty);
        return View(model);
    }
    public ViewResult Create() {
        return View();
    }
    [ActionName("Create")]
    [HttpPost, ValidateAntiForgeryToken]
    public ViewResult Create_post(TaskEntity taskEntity) {
        ctx.AddObject(Constants.TASKS_TABLE, new TaskEntity(taskEntity.Task));
        ctx.SaveChangesWithRetries();
        return RedirectToAction("Index");
    }
}

我知道这不是一个单元测试友好的,我应该通过DI的接口联系TableServiceContext实例,但当我这样做时,我也考虑使用这个WindowsAzureStorageContext类来获得TableServiceContext类的实例。

这是个好做法吗?这会不会因为我在整个应用程序生命周期中使用同一个类而对我造成任何伤害?

有什么已知的模式可以做到这一点吗?

集中CloudStorageAccount和TableServiceContext实例

我认为这样做没有任何问题。看起来这是一个很好的干净的方法。我不知道有什么已知的模式可以做到这一点,但我只是觉得昨天应该有。

我认为您可以将存储库模式用于通用数据上下文,并在其上添加通用接口。不确定这是否有帮助,但您可以参考我的博客http://blogs.shaunxu.me/archive/2010/03/15/azure-ndash-part-5-ndash-repository-pattern-for-table-service.aspx

我不认为上下文实例之间存在任何共享状态。也就是说,控制器执行的事务时间是不平凡的。你掌握上下文的时间越长,就越有可能发生冲突。我发现,将冲突和重叠降至最低的一种方法是尽可能缩短加载/更改/保存周期。

Erick