0

Estoy desarrollando una aplicación en Netcore 6, estoy implementando el patron repository y el patron Unit Of Work. Si yo ejecuto por primera vez la aplicacion y hago una consulta a travez de estos patrones a la BD todo bien, el problema es cuando quiero hacer otra consulta ya que me aparece el siguiente error

System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'FacturacionDbContext'.
   at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.Set[TEntity]()

Les dejo algunas datos del código que estoy usando.

UnitOfWork

public class UnitOfWork : IUnitOfWork
{
    private Hashtable _repositories;
    private readonly FacturacionDbContext _context;

    public UnitOfWork(FacturacionDbContext context)
    {
        
        _context = context;
    }

    public async Task<int> Complete()
    {
       return await _context.SaveChangesAsync();
    }

    public void Dispose()
    {
        _context.Dispose();
    }

    public IGenericRepository<TEntity> Repository<TEntity>() where TEntity : BaseClass
    {
        if(_repositories == null)
        {
            _repositories = new Hashtable();
        }
        var type = typeof(TEntity).Name;
        if (!_repositories.ContainsKey(type))
        {
            var repositoryType = typeof(GenericRepository<>);
            var repositoryInstance = Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _context);
            _repositories.Add(type, repositoryInstance);
        }
        return (IGenericRepository<TEntity>)_repositories[type];
    }
}

1 respuesta 1

0

Después de mucho investigar pude resolverlo El problema era que el Context lo estaba usando en el Program.Cs así:

builder.Services.AddSingleton<FacturacionDbContext>();

y lo resolví pasándolo así

builder.Services.AddTransient<FacturacionDbContext>();

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.