I am creating a server side Blazor application and want to release managed and unmanaged resource correctly. I am beginner of Blazor and not sure if what I did is correct or not. Please give me some instructions. Thanks
//This is my service for city model
namespace MyApplication.Services
{
public class BasCityService : IBasCityService, IDisposable
{
private readonly IGenericRepository<BasCity> _cityRepository;
private readonly ISysExceptionLogService _exceptionLogService;
public BasCityService(IGenericRepository<BasCity> cityRepository,
ISysExceptionLogService exceptionLogService)
{
_cityRepository = cityRepository;
_exceptionLogService = exceptionLogService;
}
public async Task<BasCity> GetByIdAsync(int id)
{
try
{
return await _cityRepository.GetByIdAsync(id);
}
catch(Exception ex)
{
await _exceptionLogService?.CreateLogAsync(ex, null,
"BasCityService.GetByIdAsync()");
return null;
}
}
//Other
............
public void Dispose()
{
_cityRepository.Dispose(true); //In GenericRepository do _dbContext.Dispose();
_exceptionLogService.Dispose();
}
}
//This is city details razor page
@page "/Base/City/CityDetails/{id:int}"
@inject IBasCityService cityService
@inject ISysExceptionLogService exceptionLogService
.........
@code {
protected override async Task OnInitializedAsync()
{
city = new BasCity();
try
{
city = await cityService?.GetByIdAsync(id);
if (city == null)
throw new NullReferenceException("Can't find City object by Id");
}
catch(Exception ex)
{
await processError?.LogError(Exception ex);
}
}
.............
//Dispose resource
// To detect redundant calls
private bool _disposedValue;
~CityDetails() => Dispose(false);
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
city = null;
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
cityService?.Dispose();
if (cityService != null) cityService = null;
exceptionLogService?.Dispose();
if (exceptionLogService != null) exceptionLogService = null;
_disposedValue = true;
}
}
}
Please tell me if CityDetails page changes to other page such as CityList page. cityService & exceptionLogService resource can be disposed correctly by the finalizer. Also what managed resource we usually need to clean up inside // TODO: dispose managed state (managed objects)? Thank you very much