title: Entity Framework initializer in console/library app
body: <p>I am currently working on a project with has a console app and few library projects. One library project is a EF code first project which contains my models and the context:</p>
  
  <pre><code>public class MyDbContext: DbContext
      {        
          public MyDbContext() : base("MyConnectionString")
          {
  
          }
  
          public DbSet&lt;File&gt; Files { get; set; }
      }
  </code></pre>
  
  <p>I also have a singleton class through which I want to access the database. The singleton looks like this:</p>
  
  <pre><code>public sealed class DbLogger : IDbLogger
      {
          private static readonly DbLogger instance = new DbLogger();
          private static MyDbContext ctx = new MyDbContext();        
  
          static DbLogger() {
              Database.SetInitializer&lt;MyDbContext&gt;(new DbInitializer());
          }
  
          private DbLogger() { }
  
          public static DbLogger Instance
          {
              get {
                  return instance;
              }
          }
  
          public void AddFile(string fileName)
          {
              ctx.Files.Add(new File() { FullPath = fileName });
          }
      }
  </code></pre>
  
  <p>The db initializer is very simple and just implements the CreateDatabaseIfNotExists. Nothing is done in Seed yet.</p>
  
  <p>In the console all which references the library project I just want to use it as:</p>
  
  <pre><code>private DbLogger logger = DbLogger.Instance;
  </code></pre>
  
  <p>and call the logger from a Task using:</p>
  
  <pre><code>logger.AddFile("myFileName");
  </code></pre>
  
  <p>When the app gets to logger.AddFile call I get the following exception:</p>
  
  <blockquote>
    <p>An exception of type 'System.InvalidOperationException' occurred in
    EntityFramework.dll but was not handled in user code</p>
    
    <p>Additional information: The context cannot be used while the model is
    being created. This exception may be thrown if the context is used
    inside the OnModelCreating method or if the same context instance is
    accessed by multiple threads concurrently. Note that instance members
    of DbContext and related classes are not guaranteed to be thread safe.</p>
  </blockquote>
  
  <p>How can I delay the using of the context until the model was created?
  I am currently a bit stuck with this and any idea on how to solve this would be appreciated.</p>
  
  <p>Thank you!</p>