I use Entity Framework 4 and ASP.NET MVC 3. I created a custom membership provider and use Ninject to insert an EFAccountRepository (Bound IAccountRepository - EFAccountRepository) into it.
This account repository has an ObjectContext. I also use this repository (and others) in my controllers. For this reason, when I attached an IContext to an ObjectContext, I set the scope to "request", so the ObjectContext lives in only one request and is shared between repositories.
Sometimes, when trying to log in, the following error occurs: "The ObjectContext instance has been deleted and can no longer be used for operations that require a connection."
I wonder how often an instance of a membership provider is created. I entered the repository into the membership provider by [Inject] repository property and calling Kernel.Inject in the Application_Start function in the global.asax file.
If the provider receives the instance more than once, I must enter it again, I suppose. However, I am not getting a null pointer exception, so I don't think so.
Update 1
Here is the code:
MyNinjectModule.cs
public override void Load() { Bind<IMyContext>().To<MyObjectContext>().InRequestScope();
Global.asax
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); var kernel = new StandardKernel(new MyNinjectModule()); ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(kernel)); kernel.Inject(Membership.Provider); }
MyMembershipProvider.cs
[Inject] public IAccountRepository accountRepository { get; set; } public override bool ValidateUser(string username, string password) {
EFAccountRepository.cs
private readonly IMyContext context; public EFAccountRepository(IMyContext context) { this.context = context; } public IQueryable<Account> Accounts { get { return context.Accounts; } }
MyObjectContext.cs
public class MyObjectContext : ObjectContext, IMyContext { public IObjectSet<Account> Accounts { get; private set; } public FlorenceObjectContext() : this("name=DomainModelContainer") { } public FlorenceObjectContext(string connectionString) : base(connectionString, "DomainModelContainer") { Accounts = CreateObjectSet<Account>(); } }
PS: I am always open for comments on my code in general;).