我已阅读此帖DbContext has been disposed and autofac,但我仍然遇到同样的错误:
由于已经处理了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);
}
}
在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);
............
............
}
答案 0 :(得分:2)
您需要使用AutoFac注册DbContext
本身并为其提供适当的生命周期。 InstancePerDependency
通常适用于存储库。
builder.RegisterType<EFDbContext>().AsSelf().InstancePerDependency();
然后,您不需要为存储库注册提供对象,只需注册类型(记住也要指定生命周期):
builder.Register<EFRepository>().As<IRepository>().InstancePerLifetimeScope();