Reputation: 7299
I have a login page in my project that the users can login using it as you can see here :
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 first time when i try to login it works fine but after log out,when i am trying to login again i got this error :
The operation cannot be completed because the DbContext has been disposed.
Here you can see my user interface and repository :
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;
}
}
}
And here is my inteface:
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);
}
here is my 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; }
}
My 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();
}
}
}
My stacktrce
[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
I finally find the point that the error happened in 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;
}
Upvotes: 0
Views: 2790
Reputation: 323
I had the same issue. After replacing in Ninject module
Bind<Context>().ToSelf().InSingletonScope();
with
Bind<Context>().ToSelf();
Context started to work properly
Upvotes: 1
Reputation: 67
I think that problem is related to registering types in IoC container. What IoC container are you using? How do you register CMSDataContext? Maybe you should use something like InstancePerRequest in AutoFac?
Upvotes: 0