在 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/