我尝试使用错误模块(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;
}
}
存储库库:
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;
谢谢您的回答。