title: Repository Pattern with MongoDB: Where to initialize the Database
body: <p>I just started to play around with MongoDB (C#) and tried to port a repository over from entity framework. I'm using the official C# driver 1.0. Now I did something like this:</p>
  
  <pre><code>internal class MongoContext
  {
      public MongoContext(string constring)
      {
          MongoServer server = MongoServer.Create(constring);
          this.myDB = server.GetDatabase("MyDB");
  
          BsonClassMap.RegisterClassMap&lt;VoyageNumber&gt;(cm =&gt;
              { cm.MapField&lt;string&gt;(p =&gt; p.Id); });
          BsonClassMap.RegisterClassMap&lt;Schedule&gt;(cm =&gt;
          { cm.MapField&lt;DateTime&gt;(p =&gt; p.EndDate); cm.MapField&lt;DateTime&gt;(p =&gt; p.StartDate); });
          BsonClassMap.RegisterClassMap&lt;Voyage&gt;(cm =&gt;
              { cm.MapIdField&lt;VoyageNumber&gt;(p =&gt; p.VoyageNumber); cm.MapField&lt;Schedule&gt;(p =&gt; p.Schedule); });
  
      }
  
      private MongoDatabase myDB;
      public MongoDatabase MyDB
      { get { return this.myDB; } }
  }
  </code></pre>
  
  <p>I'd then go on and implement the Repository like this:</p>
  
  <pre><code>public class MongoVoyageRepository : IVoyageRepository
  {
      private readonly MongoContext context;
  
      public MongoVoyageRepository(string constring)
      {
          this.context = new MongoContext(constring);
      }
  
      public void Store(Domain.Model.Voyages.Voyage voyage)
      {
  
          MongoCollection&lt;Voyage&gt; mongoVoyages = context.MyDB.GetCollection&lt;Voyage&gt;("Voyages");
  
          //store logic...
  
      }
  
  }
  </code></pre>
  
  <p>Now I'd like to know if it is a good decision to instantiate a "context" like this in terms of performance. Does it make sense to put the BsonClass Maps in there?
  Thank you for your input.</p>