在Autofac中注册的.Net Core的工作单元会引发System.ObjectDisposedException

时间:2019-05-10 16:47:12

标签: entity-framework asp.net-core autofac unit-of-work

我两次尝试通过存储单元通过工作单元进行一次HttpRequest调用,但是第二次我遇到了System.ObjectDisposedException异常。有人可以帮我吗?

我的DBContext

    private readonly string connectionString;

    public SwapDealContext(IConfigurationManager configurationManager)
        : base()
    {
        this.connectionString = configurationManager.DbConnectionString;
    }

    public SwapDealContext(DbContextOptions<SwapDealContext> options)
        : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(this.connectionString);
        }
    }
    public virtual DbSet<User> Users { get; set; }

AutoFac模块:

public class DataAccessAutoFacModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        Assembly assembly = typeof(DataAccessAutoFacModule).Assembly;
        base.Load(builder);
        builder.RegisterAssemblyTypes(assembly).AsSelf().AsImplementedInterfaces().InstancePerLifetimeScope();

        builder.RegisterType<UnitOfWork.UnitOfWork>().As<IUnitOfWork>().InstancePerLifetimeScope();
        builder.RegisterType<UnitOfWorkFactory>().As<IUnitOfWorkFactory>().InstancePerLifetimeScope();
    }
}

接口:

public interface IUnitOfWorkFactory
{
    IUnitOfWork CreateUnitOfWork();
}
public interface IUnitOfWork : IDisposable
{        
    Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken));

    T GetRepository<T>()
        where T : class;
}

示例:

public class UnitOfWork : IUnitOfWork
{
    private readonly DbContext dbContext;
    private readonly Dictionary<string, object> repositories;
    private readonly ILifetimeScope lifetimeScope;

    public UnitOfWork(
        DbContext dbContext,
        ILifetimeScope lifetimeScope)
    {
        this.dbContext = dbContext;
        this.lifetimeScope = lifetimeScope;
        this.repositories = new Dictionary<string, object>();
    }        

    public void Dispose()
    {
        this.dbContext.Dispose();
        this.repositories.Clear();
    }

    public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        try
        {
            int changes = await this.dbContext.SaveChangesAsync(cancellationToken);
            return changes;
        }
        catch (Exception ex)
        {                
            throw;
        }
    }        

    public T GetRepository<T>()
        where T : class
    {
        var typeName = typeof(T).Name;

        if (!this.repositories.ContainsKey(typeName))
        {
            T instance = this.lifetimeScope.Resolve<T>(new TypedParameter(typeof(DbContext), this.dbContext));
            this.repositories.Add(typeName, instance);
        }

        return (T)this.repositories[typeName];
    }
}
public class UnitOfWorkFactory : IUnitOfWorkFactory
{
    private readonly ILifetimeScope lifetimeScope;
    private readonly SwapDealContext context;

    public UnitOfWorkFactory(
        SwapDealContext context,
        ILifetimeScope lifetimeScope)
    {
        this.context = context;
        this.lifetimeScope = lifetimeScope;
    }

    public IUnitOfWork CreateUnitOfWork()
    {
        return new UnitOfWork(this.context, this.lifetimeScope);
    }
}

服务:

    public async Task<IList<UserDetails>> GetAllUsers()
    {
        using (var uow = this.unitOfWorkFactory.CreateUnitOfWork())
        {
            var userRepo = uow.GetRepository<IUserRepository>();

            var result = await userRepo.GetAllUsers();

            return Mapper.Map<List<UserDetails>>(result);
        }
    }

控制器

public class UserController : ControllerBase
{
    private readonly IUserService userService;
    private readonly ILogger logger;
    public UserController(IUserService userService, ILogger logger)
    {
        this.userService = userService;
        this.logger = logger;
    }
    [HttpGet]
    [Route("users")]
    [ProducesResponseType(typeof(IList<UserDetails>), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
    [AllowAnonymous]
    public async Task<IActionResult> GetUsersAnync()
    {
        try
        {
            var users = await userService.GetAllUsers();
            var users2 = await userService.GetAllUsers();

            if (!users.Any())
            {
                return NotFound($"No one user were found");
            }

            return Ok(users);
        }
        catch (Exception ex)
        {
            logger.ErrorFormat("Could not get users due to: {0}", ex, ex.Message);
            return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
        }
    }

}

StackTrace:

at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies.get_QueryProvider()
   at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ParameterExtractingExpressionVisitor..ctor(IEvaluatableExpressionFilter evaluatableExpressionFilter, IParameterValues parameterValues, IDiagnosticsLogger`1 logger, DbContext context, Boolean parameterize, Boolean generateContextAccessors)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryModelGenerator.ExtractParameters(IDiagnosticsLogger`1 logger, Expression query, IParameterValues parameterValues, Boolean parameterize, Boolean generateContextAccessors)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.System.Collections.Generic.IAsyncEnumerable<TResult>.GetEnumerator()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.IncludableQueryable`2.System.Collections.Generic.IAsyncEnumerable<TEntity>.GetEnumerator()
   at System.Linq.AsyncEnumerable.Aggregate_[TSource,TAccumulate,TResult](IAsyncEnumerable`1 source, TAccumulate seed, Func`3 accumulator, Func`2 resultSelector, CancellationToken cancellationToken)
   at SwapDeal.DataAccess.Repositories.UserRepository.GetAllUsers() in C:\Users\osmachenko\personal\VAO\SwapDeal.DataAccess\Repositories\UserRepository.cs:line 23
   at SwapDeal.BizLogic.Services.UserService.GetAllUsers() in C:\Users\osmachenko\personal\VAO\SwapDeal.BizLogic\Services\UserService.cs:line 40
   at SwapDeal.WebApi.Controllers.UserController.GetUsersAnync() in C:\Users\osmachenko\personal\VAO\SwapDeal.WebApi\Controllers\UserController.cs:line 37

因此,当我在Controller中两次调用GetAllUsers方法时,出现了System.ObjectDisposedException。

1 个答案:

答案 0 :(得分:0)

看到上下文被丢弃的原因是因为您正在丢弃它。

如果我们追溯到...

  • 您在Autofac中注册的每种类型似乎都已注册InstancePerLifetimeScope。这意味着您将在整个生命周期内获得一个。在ASP.NET Core中,每个请求(基本上)等于一个实例。
  • 控制器将在其控制器中获得IUserService。我们没有看到整个IUserService的样子,但是在示例代码中确实看到了GetAllUsers
  • GetAllUsers将操作包装在using语句中-它先创建,然后处置工作单元。
  • UnitOfWork的构造函数中,您传入DbContext-一个实例 ,您将收到该请求,然后...
  • 您在UnitOfWork.Dispose中处置DbContext。由于该GetAllUsers语句,这种情况发生在using的结尾。
    public async Task<IList<UserDetails>> GetAllUsers()
    {
        // The factory creates the unit of work here...
        using (var uow = this.unitOfWorkFactory.CreateUnitOfWork())
        {
            var userRepo = uow.GetRepository<IUserRepository>();

            var result = await userRepo.GetAllUsers();

            return Mapper.Map<List<UserDetails>>(result);
            // At the end of this using statement, the unit of work gets disposed
            // and in UnitOfWork.Dispose() you dispose of the DbContext.
        }
    }

如果要两次调用该操作,则需要:

  • 不要在工作单元结束时处理上下文; OR
  • 为每个工作单元提供自己的数据库上下文。