DbContext lifetime beginning after user login

276 views Asked by At

Typically DbContext and ConnectionString are set at application start. In my ASP.NET MVC application I have a database with Users and ConnectionStrings data and depending on which user logs in, I want to use their ConnectionString to connect them to a secondary DbContext.

I tried to use DbContextScope but with the current implementation it doesn't seem to support this scenario. (I posted a related question for that here).

So in lifecycle of an ASP.NET MVC application how can we make sure the secondary DbContext is instantiated only after the user is logged in? What's the correct way to manage the lifecycle of DbContext here.

Thanks!

1

There are 1 answers

1
Martin Noreke On BEST ANSWER

There is an overload for DbContext that takes in the connection string. With this, you could add a constructor to pass in the secondary connection string based upon the user that is accessing data.

public MySecondaryDbContext(string connectionString)
        : base(connectionString)
    {
    }

Alternatively, you could pass in a user object that has the connection string to use.

public MySecondaryDbContext(UserObject user)
        : base(user.ConnectionString)
    {
    }

Hope this helps you out.

Update for Lifecycle

As to the lifecycle, you could use something like this with a null check from the calling side.

public static MySecondaryDbContext GetContextForUser(UserObject user)
{
     if(user.IsLoggedIn)
          return null;

     return new MySecondaryDbContext(user.ConnectionString);
}

private MySecondaryDbContext(string connectionString)
        : base(connectionString)
{
}

This will prevent the secondary DbContext from being instantiated prior to the user being logged in.