在ASP.NET MVC 3 Web角色,我已經意識到,我一直在寫下面的代碼很多:集中CloudStorageAccount和TableServiceContext實例
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
類的實例。
這是一個很好的做法嗎?它會在任何時候傷害到我,因爲我在整個應用程序生命週期中使用了同一個類。
有什麼訣竅模式來做到這一點?
Thanks!爲什麼我問這個問題的原因是,我不能夠static'關鍵字'的全部功能。我在想,如果我這樣做,是否會遇到問題。 – tugberk 2012-02-02 18:37:43