Autofac DbContext已被处置 [英] Autofac DbContext has been disposed
问题描述
我已经阅读了这篇帖子 DbContext已被处置并且是autofac ,但是我仍然遇到相同的错误:
I've read this post DbContext has been disposed and autofac but I'm still getting the same error:
由于已处理DbContext,因此无法完成该操作.
The operation cannot be completed because the DbContext has been disposed.
public class EFRepository : IRepository
{
private EFDbContext context;
public EFRepository(EFDbContext ctx)
{
context = ctx;
}
public TEntity FirstOrDefault<TEntity>(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includes)
where TEntity : class, IContextEntity
{
IQueryable<TEntity> query = includes.Aggregate<Expression<Func<TEntity, object>>, IQueryable<TEntity>>
(context.Set<TEntity>(), (current, expression) => current.Include(expression));
return query.FirstOrDefault(predicate);
}
}
在Global.asax中
And in the Global.asax
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.Register<IRepository>(c => new EFRepository(new EFDbContext()));
ILifetimeScope container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
控制器注入:
public class AccountController : Controller
{
private readonly IRepository repository;
private readonly IMembershipService membershipService;
public AccountController(IRepository repo, IMembershipService mmbrSvc)
{
repository = repo;
membershipService = mmbrSvc;
}
[HttpPost]
public ActionResult Login(LoginViewModel viewModel)
{
if (!ModelState.IsValid)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
string returnUrl = (string)TempData["ReturnUrl"];
LoginDto accountDto = viewModel.GetLoginStatus(repository, membershipService, returnUrl);
string accountDtoJson = JsonHelper.Serialize(accountDto);
return Content(accountDtoJson, "application/json");
}
}
然后在LoginViewModel中:
Then in LoginViewModel:
public LoginDto GetLoginStatus(IRepository repo, IMembershipService mmbrSvc, string returnUrl)
{
repository = repo;
membershipService = mmbrSvc;
User user = repository.FirstOrDefault<User>(x => x.Username == Username, x => x.Membership);
............
............
}
推荐答案
您需要在AutoFac中注册DbContext
本身,并为其赋予适当的生命周期. InstancePerDependency
通常适合存储库.
You need to register the DbContext
itself with AutoFac and give it the appropriate lifetime. InstancePerDependency
is usually fine for repositories.
builder.RegisterType<EFDbContext>().AsSelf().InstancePerDependency();
然后,您不需要给存储库注册一个对象,只需注册类型(记住也要指定生存期):
Then, you don't need to give the repository registration an object, just register the type (remembering to specify the lifetime as well):
builder.Register<EFRepository>().As<IRepository>().InstancePerLifetimeScope();
这篇关于Autofac DbContext已被处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!