简体   繁体   中英

Azure Table Storage best practice for ASP.NET MVC/WebApi

What are the best practices for connecting to a Azure Table Storage from a ASP.NET MVC or Web API app?

Right now I've made a StorageContext class which holds a reference to the CloudStorageAccount and CloudTableClient , like this:

public class StorageContext
{
    private static CloudStorageAccount _storageAccount;
    private static CloudTableClient _tableClient;

    public StorageContext() : this("StorageConnectionString") { }

    public StorageContext(string connectionString)
    {
        if (_storageAccount == null)
            _storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings[connectionString].ConnectionString);

        if (_tableClient == null)
            _tableClient = _storageAccount.CreateCloudTableClient();
    }

    public CloudTable Table(string tableName)
    {
        var table = _tableClient.GetTableReference(tableName);

        table.CreateIfNotExists();

        return table;
    }
}

And my controller I'm using it like this:

public class HomeController : ApiController
{
    private StorageContext db;

    public HomeController() : this(new StorageContext()) { }

    public HomeController(StorageContext context)
    {
        this.db = context;
    }

    public IHttpActionResult Get()
    {
        var table = db.Table("users");
        var results = (from user in table.CreateQuery<User>()
                       select user).Take(10).ToList();

        return Ok<List<User>>(results);
    }
}

Is this the preferred way of doing it?

The API is going to be used on a high traffic site with > 1000 req/sec.

I also need unit tests. Using it like above it I can pass in another connString name and instead connect to the Azure Storage emulator in my unit tests.

Am I on the right track or are there better ways to connect?

Actually your question

What are the best practices for connecting to a Azure Table Storage from a ASP.NET MVC or Web API app?

could be restated like "What are the best practices to use data access layer in web application". It is the same.

You can find a lot of answers about data access layer best practices. But iron rule here keep your data access layer separated from your controller or presentation. The best way to use it through Model in scope of MVC pattern, or you can think about Repository and/or Unit of work pattern if you like them.

In your example your data access logic is already wrapped in StorageContext, which is fine, I would additionally extract interface and use DI/IoC and dependency resolver for it. That's all when speaking about your code snippet. You are on right way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM