3
votes

We are building a multi-tenant database application utilizing ASP.NET MVC, the Entity Framework Code First, and the soon to be released SQL Azure Federations. Our repository accepts a DbContext as a constructor argument that is injected using Ninject. The problem is that the DbContext has an int constructor argument to specify the account id that will be used for the requests made with that context. Something like this:

public class DatabaseContext : DbContext
{
     public DatabaseContext(int accountId)
     {
          // Code here to ensure we only work with data associated with 
          // the account identified by accountId
     }
}

The value for the account id will be stored in a Session variable. The question is how do we get Ninject to inject a value from Session into the constructor when it creates a new instance of DatabaseContext?

Or is there another way I should go about injecting the account id into the DbContext?

1

1 Answers

6
votes

There are a few ways. I like using the .ToMethod approach.

Bind<DatabaseContext>().ToMethod(
    c => new DatabaseContext((int)HttpContext.Current.Session["Acct"]);

Though to solve this particular problem, I've found it better to create an ISessionManager service that has session-based data on it. Anything that wants, e.g., an accountId would have this service injected into the constructor, and access its AccountId property when it needs an account ID.