2012-02-02 43 views
3

在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類的實例。

這是一個很好的做法嗎?它會在任何時候傷害到我,因爲我在整個應用程序生命週期中使用了同一個類。

有什麼訣竅模式來做到這一點?

回答

1

我沒有看到這樣做的任何問題。看起來像一個乾淨的方式來做到這一點。我不知道有一個已知的模式可以做到這一點,但只是認爲應該在昨天。

+0

Thanks!爲什麼我問這個問題的原因是,我不能夠static'關鍵字'的全部功能。我在想,如果我這樣做,是否會遇到問題。 – tugberk 2012-02-02 18:37:43

0

我不相信有上下文的實例之間的任何共享的狀態。據說,控制器執行的交易時間並不重要。持續的時間越長,您就越有可能發生衝突。我發現一個方式,讓衝突和重疊到最低限度是保持負載/變更/保存週期越短越好。

Erick