[英]Autofac DbContext has been disposed
I've read this post DbContext has been disposed and autofac but I'm still getting the same error:我已经阅读了这篇文章DbContext 已被处置和 autofac但我仍然遇到同样的错误:
The operation cannot be completed because the DbContext has been disposed.
操作无法完成,因为 DbContext 已被释放。
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);
}
}
And in the Global.asax在 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));
Controller injection: Controller 注入:
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");
}
}
Then in LoginViewModel:然后在 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);
............
............
}
You need to register the DbContext
itself with AutoFac and give it the appropriate lifetime. 您需要在AutoFac中注册
DbContext
本身,并为其赋予适当的生命周期。 InstancePerDependency
is usually fine for repositories. InstancePerDependency
通常适用于存储库。
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();
Use builder.RegisterType<EFDbContext>().AsSelf().SingleInstance();
使用
builder.RegisterType<EFDbContext>().AsSelf().SingleInstance();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.