由于DbContext已在mvc

时间:2015-11-19 05:45:01

标签: c# asp.net-mvc entity-framework dispose dbcontext

我的项目中有一个登录页面,用户可以使用它登录,如您所见:

public class LoginController : Controller
    {
        private IUserRepository _iuserRepository;
        public LoginController(IUserRepository userRepository)
        {
            _iuserRepository = userRepository;
        }
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string email, string password, string returnUrl)
        {
            if (_iuserRepository.CheckAuth(email, password))
            {

                FormsAuthentication.SetAuthCookie(email, true);
                if (shouldRedirect(returnUrl))
                {
                    return Redirect(returnUrl);
                }


                return RedirectToAction("Index", "Home", new {Area = "FAdmin"});

            }
            else
            {

                return RedirectToAction("Index");
            }



        }

        [HttpGet]
        public ActionResult LogOut()
        {
            DomainClass.CMS.User user = _iuserRepository.FindByEmail(User.Identity.Name).First();
            user.LastLogin = DateTime.Now;
            _iuserRepository.Save();

            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Login", new { Area = "FAdmin" });
        }

我第一次尝试登录时工作正常但在注销后,当我尝试再次登录时出现此错误:

 The operation cannot be completed because the DbContext has been disposed. 

在这里,您可以看到我的用户界面和存储库:

 public class UserRepository:IUserRepository
    {
       public CMSDataContext _ctx;
        public UserRepository (CMSDataContext ctx)
        {
            _ctx = ctx;
        }
        public IQueryable<User> GetUsers()
        {
           return _ctx.Users;
        }

        public bool Save()
        {
            try
            {
                return _ctx.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }

        public bool AddUser(User newUser)
        {
            try
            {
                _ctx.Users.Add(newUser);
                return true;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }

        public bool Delete(User deletedUser)
        {
            try
            {
                _ctx.Users.Remove(deletedUser);
                return true;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }


        public bool Edit(User UpdatedValue)
        {
            try
            {
                _ctx.Entry(UpdatedValue).State = System.Data.Entity.EntityState.Modified;
                return true;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }


        public IQueryable<User> Search(string Value)
        {
            return _ctx.Users.Where(i => i.Fullname.Contains(Value));

        }

        public IQueryable<User> FindById(int Id)
        {
            return _ctx.Users.Where(i => i.Id == Id);
        }


        public string[] ReturnRole(string Email)
        {

                    string[] res = new string[1];

                    //res[0] = FindByEmail(Email).First().Permission;
                 //   res[0] = "administrator";//member
                    User a=_ctx.Users.Where(i => i.Email == Email).ToList().First();
                    res[0] = a.Permission;
                    return res;

        }


        public IQueryable<User> FindByEmail(string Email)
        {
            return _ctx.Users.Where(i => i.Email == Email);
        }


        public bool CheckAuth(string Email, string password)
        {
            try
            {
                if (_ctx.Users.Where(i => i.Email == Email && i.Password == password && i.Enable=="فعال").Count() == 1)
                    return true;
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }
    }

这是我的接口:

  public interface  IUserRepository
    {
        IQueryable<User> GetUsers();
        bool Save();
        bool AddUser(User newUser);
        bool Delete(User deletedUser);
        bool Edit(User UpdatedValue);
        IQueryable<User> Search(string Value);
        IQueryable<User> FindById(int Id);
        IQueryable<User> FindByEmail(string Email);
        bool CheckAuth(string Email,string password);
       string[] ReturnRole(string Email);
    }

这是我的dbcontext:

  public class CMSDataContext : DbContext
    {
        public CMSDataContext()
            : base("DefaultConnection")
        {
            this.Configuration.LazyLoadingEnabled = false;
            this.Configuration.ProxyCreationEnabled = false;

            Database.SetInitializer(
                new MigrateDatabaseToLatestVersion<CMSDataContext, CMSMigrationsConfiguration>()
                );
        }

        public DbSet<User> Users { get; set; }
        public DbSet<News> Newses { get; set; }
        public DbSet<Configuration> Configurations { get; set; }
        public DbSet<Project> Projects { get; set; }
        public DbSet<Comment> Comments { get; set; }
        public DbSet<CompanyMember> CompnayMembers { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<Gallery> Galleries { get; set; }
        public DbSet<Goal> Goals { get; set; }
        public DbSet<Menu> Menus { get; set; }
        public DbSet<Page> Pages { get; set; }
        public DbSet<Partner> Partners { get; set; }
        public DbSet<SlideShow> Slideshows { get; set; }
        //--------------------------lizing part domain class
        public DbSet<Group> Groups { get; set; }
        public DbSet<GroupFile> GroupFiles { get; set; }
        public DbSet<Request> Requests { get; set; }
        public DbSet<RequestFile> RequestFiles { get; set; }
        public DbSet<RequestComment> RequestComments { get; set; }

    }

我的ninject

using Core.CMS;
using Inf.CMS;
using InfCMSDataLayer;
using Lizing.Inf;
using Lizing.Repository;
using Repository.CMS;
using RepositoryCMS;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MTBCO.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(MTBCO.App_Start.NinjectWebCommon), "Stop")]

namespace MTBCO.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;

    public static class NinjectWebCommon 
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<CMSDataContext>().To<CMSDataContext>().InRequestScope();
            kernel.Bind<IUserRepository>().To<UserRepository>().InRequestScope();
            kernel.Bind<INewsRepository>().To<NewsRepository>().InRequestScope();
            kernel.Bind<IConfigurationRepository>().To<ConfigurationRepository>().InRequestScope();
            kernel.Bind<IGoalRepository>().To<GoalRepository>().InRequestScope();
            kernel.Bind<IPartnerRepository>().To<PartnerRepository>().InRequestScope();
            kernel.Bind<ICalenderRepository>().To<CalenderRepository>().InRequestScope();
            kernel.Bind<ICustomerRepository>().To<CustomerRepository>().InRequestScope();
            kernel.Bind<ISlideshowRepository>().To<SlideshowRepository>().InRequestScope();
            kernel.Bind<IProjectRepository>().To<ProjectRepository>().InRequestScope();
            kernel.Bind<IGalleryRepository>().To<GalleryRepository>().InRequestScope();
            kernel.Bind<ICompanyMemberRepository>().To<CompanyMemberRepository>().InRequestScope();
            kernel.Bind<ICommentRepository>().To<CommentRepository>().InRequestScope();
            kernel.Bind<IPageRepository>().To<PageRepository>().InRequestScope();
            kernel.Bind<IMenuRepository>().To<MenuRepository>().InRequestScope();
            kernel.Bind<IGroupRepository>().To<GroupRepository>().InRequestScope();
            kernel.Bind<IRequestRepository>().To<RequestRepository>().InRequestScope();
            kernel.Bind<IRequestFileRepository>().To<RequestFileRepository>().InRequestScope();
            kernel.Bind<IGroupFileRepository>().To<GroupFileRepository>().InRequestScope();
            kernel.Bind<IRequestCommentRepository>().To<RequestCommentRepository>().InRequestScope();





        }        
    }
}

我的堆栈

[InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.]
   System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +762
   System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() +28
   System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +52
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +369
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
   Repository.CMS.UserRepository.ReturnRole(String Email) +348
   MTBCO.MyRoleProvider.GetRolesForUser(String email) +11
   System.Web.Security.RolePrincipal.IsInRole(String role) +9625187
   System.Linq.Enumerable.Any(IEnumerable`1 source, Func`2 predicate) +146
   System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +197
   System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +159
   System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +96
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +381
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +49
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

我终于发现错误发生在userrepository .why?

 public string[] ReturnRole(string Email)
        {

                    string[] res = new string[1];

                    //res[0] = FindByEmail(Email).First().Permission;
                 //   res[0] = "administrator";//member
                    User a=_ctx.Users.Where(i => i.Email == Email).ToList().First();
                    res[0] = a.Permission;
                    return res;

        }

2 个答案:

答案 0 :(得分:1)

我有同样的问题。更换Ninject模块后

        Bind<Context>().ToSelf().InSingletonScope();

        Bind<Context>().ToSelf();

上下文开始正常工作

答案 1 :(得分:0)

我认为该问题与在IoC容器中注册类型有关。您使用的是什么IoC容器?你如何注册CMSDataContext?也许你应该在AutoFac中使用像InstancePerRequest这样的东西?