我使用Entity Framework 4和ASP.NET MVC 3.我创建了一个自定义成员资格提供程序并使用Ninject将EFAccountRepository注入其中(将IAccountRepository绑定到EFAccountRepository).
此帐户存储库中注入了ObjectContext.我还在我的控制器中使用此存储库(和其他人).出于这个原因,当我将IContext绑定到我的ObjectContext时,我将范围设置为"每个请求",因此ObjectContext只存在于一个请求中并在存储库之间共享.
尝试登录时,我有时会收到以下错误:"ObjectContext实例已被处理,不能再用于需要连接的操作."
我想知道会员提供者多久被实例化一次.我通过在global.asax文件中标记存储库属性[Inject]并调用Kernel.Inject该Application_Start函数,将存储库注入到成员资格提供程序中.
如果提供者不止一次实例化,我想再次注入.但是,我没有得到空指针异常,所以我不认为是这样.
这是一些代码:
MyNinjectModule.cs
public override void Load()
{
Bind<IMyContext>().To<MyObjectContext>().InRequestScope();
// put bindings here
Bind<IAccountRepository>().To<EFAccountRepository>
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
MyMembershipProvider.cs
[Inject]
public IAccountRepository accountRepository { get; set; }
public override bool ValidateUser(string username, string password)
{
// I get the exception here.
return (from a in accountRepository.Accounts
where a.UserName == username …Run Code Online (Sandbox Code Playgroud) ObjectContext实例已在InRequestScope中处理!
我在网上尝试了几个小时试图解决问题.
ObjectContext实例已被释放,不能再用于需要连接的操作.
我发现了几个文章和帖子中包含了同样的问题这个,这个,这个和这个
我尝试了所有方法,但总是发生错误.
上下文
public class BindSolutionContext : DbContext
{
public DbSet<Project> Projects { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<ProjectImage> ProjectImages { get; set; }
public BindSolutionContext()
: base("name=Data")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<BindSolutionContext>());
}
}
Run Code Online (Sandbox Code Playgroud)
Ninject
kernel.Bind<BindSolutionContext>().ToSelf().InRequestScope();
kernel.Bind<IProjectRepository>().To<ProjectRepository>().InRequestScope();
kernel.Bind<IUserRepository>().To<UserRepository>().InRequestScope();
kernel.Bind<IRoleRepository>().To<RoleRepository>().InRequestScope();
kernel.Bind<IAddressRepository>().To<AddressRepository>().InRequestScope();
kernel.Bind<IProjectImageRepository>().To<ProjectImageRepository>().InRequestScope();
Run Code Online (Sandbox Code Playgroud)
知识库
public class ProjectRepository : IProjectRepository
{
private readonly …Run Code Online (Sandbox Code Playgroud) dependency-injection ninject custom-membershipprovider asp.net-mvc-3 dbcontext