Hi All!

Last time I rambled a little bit about TDD and how to implement a very simple MongoDB repository.

This time I want to introduce you to my cool friend, DbContext. The basic idea is to have an interface exposing all the collection on your db, or, in our case, all the repositories. Take a look at this:

public interface IDbContext
IRepository<Entities.Post> Posts { get; }
IRepository<Entities.User> Users { get; }
IRepository<Entities.Tag> Tags { get; }
IRepository<Entities.Taxonomy> Taxonomies { get; }

view raw
hosted with ❤ by GitHub

( I will leave to you the definition of the entities ). The implementation is pretty straightforward:

public class DbContext : IDbContext
public DbContext(IRepositoryFactory repoFactory, string connectionString, string dbName)
if (string.IsNullOrWhiteSpace(connectionString))
throw new ArgumentNullException("connectionString");
if (string.IsNullOrWhiteSpace(dbName))
throw new ArgumentNullException("dbName");
this.Posts = repoFactory.Create<Entities.Video>(new RepositoryOptions(connectionString, dbName, "posts"));
this.Users = repoFactory.Create<Entities.User>(new RepositoryOptions(connectionString, dbName,"users") );
this.Tags = repoFactory.Create<Entities.Tag>(new RepositoryOptions(connectionString, dbName, "tags"));
this.Taxonomies = repoFactory.Create<Entities.Taxonomy>(new RepositoryOptions(connectionString, dbName, "taxonomies"));
public IRepository<Entities.Post> Posts { get; private set; }
public IRepository<Entities.User> Users { get; private set; }
public IRepository<Entities.Tag> Tags { get; private set; }
public IRepository<Entities.Taxonomy> Taxonomies { get; private set; }

view raw
hosted with ❤ by GitHub

A couple of details worth noting here:
1) the repositories are exposed as interfaces and not as specific implementation, making tests easier to write
2) again, all the repositories are generated via a factory, injected directly in the ctor.

The Factory Pattern allows us to add more repositories without much hassle and, moreover, to inject a “fake” factory during our tests.

Next time we’ll discuss about how to implement a factory for our repo-needs 🙂