c# - 集中 CloudStorageAccount 和 TableServiceContext 实例

标签 c# asp.net-mvc azure azure-storage azure-table-storage

在 ASP.NET MVC 3 Web Role 中,我意识到我已经编写了很多下面的代码:

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();
        } 
    }
}

而且,我在我的 Controller 中使用它,如下所示:

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 接口(interface)访问该 TableServiceContext 实例,但是当我这样做时,我考虑使用这个 WindowsAzureStorageContext > 类以及获取 TableServiceContext 类的实例。

这是一个好的做法吗?因为我在整个应用程序生命周期中使用相同的类,它会在任何时候伤害我吗?

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

最佳答案

我认为这样做没有任何问题。看起来是一个很好的干净的方法。我不知道执行此操作的已知模式,但只是想昨天应该有。

关于c# - 集中 CloudStorageAccount 和 TableServiceContext 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9112560/

相关文章:

c# - 如何远程访问工作组计算机中远程主机的 Windows 服务?

c# - 如何从 SqlDataReader 返回单个值?

c# - 如何在并行 block 中正确继承线程文化?

asp.net-mvc - 渲染 View 需要很长时间

asp.net-mvc - "return View()"和 "return PartialView()"有什么区别

azure - 是否可以从 Application Insights 中排除某个 url?

c# - 如何在 C# 中使用正则表达式解析 OData $filter?

c# - 具有两个接口(interface)的 Prism 7 Singleton

azure - 创建 Azure 策略以阻止将角色分配给某些主体类型,由指定用户创建的情况除外

azure - 在流分析查询中将字符串转换为日期时间