0

i have autofac with context

builder.RegisterType<WebRepositoryContext>().WithParameter("mode", (GlobalVariables.DataBaseMode)).InstancePerLifetimeScope();

switch initializer

    private static void InitializeDataStore()
    {
        switch (GlobalVariables.DataBaseMode)
        {
            case DataBaseMode.MsSql:
            {
                Database.SetInitializer(new MigrateDatabaseToLatestVersion<WebRepositoryContext, Repository.Migrations.Configuration>());

                var configuration = new Repository.Migrations.Configuration();
                var migrator = new DbMigrator(configuration);
                if (migrator.GetPendingMigrations().Any())
                    migrator.Update();
            }
                break;
            case DataBaseMode.Postgres:
            {
                Database.SetInitializer(new PostgresInitializer());
            }

                break;
        }
    }

initializer

public class PostgresInitializer : IDatabaseInitializer<WebRepositoryContext>
{
    public void InitializeDatabase(WebRepositoryContext context)
    {
        //create database
        var h = new PostgresHelper(context);
        h.Create();

        //seed database
        Seed(context);
    }

    protected virtual void Seed(WebRepositoryContext context)
    {

        var seed = new WebRepositorySeed(context);
       seed.Start();
    }
}

and when i try to get data in project, like var mainPage = DataContext.MainPage.First(); in Home Controller i got "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."

public class HomeController : BaseController where public WebRepositoryContext DataContext { get; set; }

probably, initialiser dispose context, which is created by autofac. how to prevent it?

vlukham
  • 409
  • 4
  • 11

1 Answers1

0

It's not a good (mmmm, it's really a very very bad idea) to have a DbContext which lasts for the lifetime of the application:

  • The DbContext should be as short-lived as possible. Take into account that it caches data and tracks changes. So, as time goes by and operations are donde in the same context, things tsrat to get very complicated
  • Using a sinlge DbContext will provoke concurrency problems: DbContext is not thread-safe. Only its static methods are. So, if you use a single instance for all the MVC threads you'll soon get into all kind of trouble

I prefer to have even a shorterlife time, but things will improve if you use InstancePerHttpRequest. At least, the DbContext life will be shorter, and you'll avoid the concurrency errors.

JotaBe
  • 38,030
  • 8
  • 98
  • 117