C#C
C#2y ago
Unmei

How to effectively dispose unmanaged resources?

i have some questions about disposing objects in .NET.
I work with a .NET API that connects to a SQL Server database via Entity Framework.
Basically, the hierarchy of calls are: Controller -> Scoped Service -> Scoped Repository -> DbContext.
As we are increasing number of users of the API and our application isn't very optmized, i went into studying about disposing objects, specially unmanaged resources (those not "deletable" by GC right? How to know if a object is unmanaged btw?).
I wrote some questions in the code snippet bellow. As I'm still new to this (never needed to write explicitly dispose methods before), I'm open to opinions and experiences you all had in your projects and investigations!

// UserService and BookService are scoped services. Are these unmanaged resources?
public class UserService : IDisposable
{
    private IBookService _bookService;
    private IUserRepository _userRepository;

    public UserService(
        IBookService bookService,
        IUserRepository userRepository
    ) {
        _bookService = bookService;
        _userRepository = userRepository;
    }

    // ... methods

    public void Dispose()
    {
        // is it effective to use Dispose like that?
        // are _bookService and _userRepository unmanageable resources?
        _bookService?.Dispose();
        _userRepository?.Dispose();

        // is it needed/effective to set those to null?
        _bookService = null;
        _userRepository = null;
      }
}

// UserRepository is scoped
public class UserRepository : IUserRepository, IDisposable
{
    private readonly DbContext _context;

    public UserRepository(DbContext context)
    {
        _context = context;
    }

    // ... methods

    public void Dispose()
    {
        // is it effective to use Dispose like that?
        _context?.Dispose();
        
        // is it needed/effective to set it to null?
        _context = null;
    }
}
Was this page helpful?