我尝试使用错误模块(Application_Error),HttpModuleMagic.MVC3,Ninject.MVC3,EF 4.1进行自定义错误处理(http://perspectivespace.com/100497697)。不幸的是,当我想将错误记录到数据库时,它会给出以下错误消息: “由于已经处理了DbContext,因此无法完成操作。”
有人可以帮帮我吗?
public class ErrorHandlerHttpModule : IHttpModule
{
private const string ErrorControllerRouteName = "Error";
private IErrorRepository errorRepo;
private IUserRepository userRepo;
// private IUserRepository UserRepository;
public ErrorHandlerHttpModule(IErrorRepository er, IUserRepository ur)
{
errorRepo = er;
userRepo = ur;
}
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.Error += Application_Error;
}
private void Application_Error(object sender, EventArgs e)
{
// Get the last error.
var exception = HttpContext.Current.Server.GetLastError();
...
error.User = userRepo.GetUserByName(name);
...
在NinjectWebCommon.cs中:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IErrorRepository>().To<ErrorRepository>().InRequestScope();
kernel.Bind<IUserRepository>().To<UserRepository>().InRequestScope();
kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>().InRequestScope();
kernel.Bind<IDisposable>().To<Disposable>().InRequestScope();
kernel.Bind<IHttpModule>().To<ErrorHandlerHttpModule>();
}
...和UserRepository类:
public class UserRepository : RepositoryBase<User>, IUserRepository
{
public UserRepository(IDatabaseFactory databaseFactory)
: base(databaseFactory)
{
}
public User GetUserByName(string name)
{
User us = null;
try
{
us = dataContext.Users.Where(u => u.UserName.Equals(name)).FirstOrDefault() as User;
}
catch (Exception ex)
{
}
return us;
}
}
RepositoryBase:
public abstract class RepositoryBase<T> where T : class
{
protected TestContext dataContext;
private readonly IDbSet<T> dbset;
protected RepositoryBase(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.Set<T>();
}
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
protected TestContext DataContext
{
get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}
...
和DatabaseFactory类:
public class DatabaseFactory : Disposable, IDatabaseFactory
{
private TestContext dataContext;
public TestContext Get()
{
return dataContext ?? (dataContext = new TestContext());
}
protected override void DisposeCore()
{
if (dataContext != null)
dataContext.Dispose();
}
}
此行潜水错误:
dataContext.Users.Where(u => u.UserName.Equals(name)).FirstOrDefault() as User;
感谢您的回答。
答案 0 :(得分:3)
protected override void DisposeCore()
{
if (dataContext != null)
{
dataContext.Dispose();
dataContext = null;
}
}
答案 1 :(得分:-1)
原因是您的LINQ查询被延迟,换句话说,它不会在您的&#34; UserRepository&#34;中运行。但只在调用代码中。因此DBContext在执行时已经被处理掉了。您可以通过更改
强制它立即执行us = dataContext.Users.Where(u => u.UserName.Equals(name)).FirstOrDefault() as User
到
us = dataContext.Users.Where(u => u.UserName.Equals(name)).ToList().FirstOrDefault() as User