Running NBlog on Windows Azure
In an attempt to get back into some regular cadence of blogging, I decided to refresh the look and functionality of my blog. I decided to switch over to NBlog as my blogging engine and Windows Azure as my host. Getting NBlog up and running on Windows Azure turned out to be pretty simple and only required one key change - the repository.
Azure Repository
NBlog uses a repository pattern for persisting settings and blob entries. Currently it offers providers for Json file storage, Sql database, and MongoDb. I could have opted to attempt to use the Sql repository to use Sql Azure - but I like the simplicity of storing data as .json files so I chose to use Azure Blob Storage.
Getting NBlog up and running on Azure really was as simple as replacing the repository by creating one class: AzureBlobRepository. I decided to base the design on the existing Json file repository but instead of using directories and json files for storage, I would use Azure blob storage directories and blobs to store the data still in Json).
Here is the save method as an example of how simple it was to implement.
public class AzureBlobRepository : IRepository
{
...
public void Save<TEntity>(TEntity item) where TEntity : class, new()
{
var json = JsonConvert.SerializeObject(item, Formatting.Indented);
var key = _keys.GetKeyValue(item).ToString();
string relativePath = GetItemPath<TEntity>(key);
CloudBlob blob = _container.GetBlobReference(relativePath);
blob.UploadText(json);
}
---
}
This method simply takes an object, serializes it to Json, and stores it as a blob in Azure using a CloudBlobContainer and a CloudBlob. You can download the entire AzureBlobRepository implementation here. (This helper file is also required)
Configuration
To configure NBlog to use the new repository you just need to edit the IOC container registration in the global.asax.cs file. Add the following registration:
builder.RegisterType<AzureBlobRepository>().Named<IRepository>("azure").InstancePerHttpRequest().WithParameters(new[] {
new NamedParameter("keys", repositoryKeys),
new NamedParameter("tenantSelector", new HttpTenantSelector())
});
Next, set the new repository as the one to be returned at runtime:
builder.RegisterType<ConfigService>().As<IConfigService>().InstancePerLifetimeScope()
.WithParameter(GetResolvedParameterByName<IRepository>("azure"));
builder.RegisterType<EntryService>().As<IEntryService>().InstancePerLifetimeScope()
.WithParameter(GetResolvedParameterByName<IRepository>("azure"));
And that is basically all of the changes needed to run NBlog on Windows Azure. I think the simplicity of this change speaks to the power of the repository pattern when used correctly.