Autofac DbContext 已被释放

本文关键字:释放 DbContext Autofac | 更新日期: 2023-09-27 18:34:40

我已经阅读了这篇文章,DbContext已被处置和autofac,但我仍然收到相同的错误:

无法完成该操作,因为已释放数据库上下文。

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中

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 中:

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 已被释放

您需要

向AutoFac注册DbContext本身,并为其提供适当的生存期。 InstancePerDependency通常适用于存储库。

builder.RegisterType<EFDbContext>().AsSelf().InstancePerDependency();

然后,你不需要给仓库注册一个对象,只需注册类型(记住也要指定生存期(:

builder.Register<EFRepository>().As<IRepository>().InstancePerLifetimeScope();

使用 builder.RegisterType<EFDbContext>().AsSelf().SingleInstance();