C
C#3y ago
nobody

Will this service will be disposed using DependencyInjection?

I have the following class which is added to the default DI-container (Blazor WASM)
public class ClientGrpcService<TService> : IClientGrpcService<TService>, IDisposable where TService : class
{
private readonly GrpcChannel _channel;
private readonly TService _service;

public ClientGrpcService()
{
_channel = GrpcChannel.ForAddress("https://localhost:7046");
_service = _channel.CreateGrpcService<TService>();
}

public TService Service => _service;

public void Dispose()
{
_channel.Dispose();
}
}
public class ClientGrpcService<TService> : IClientGrpcService<TService>, IDisposable where TService : class
{
private readonly GrpcChannel _channel;
private readonly TService _service;

public ClientGrpcService()
{
_channel = GrpcChannel.ForAddress("https://localhost:7046");
_service = _channel.CreateGrpcService<TService>();
}

public TService Service => _service;

public void Dispose()
{
_channel.Dispose();
}
}
and In my classes I simply do
public TestClass(IClientGrpcService<Example> service)
{
...
}
public TestClass(IClientGrpcService<Example> service)
{
...
}
the TestClass itself will be instantiated by the DI as well. Will the disposed method of the GrpcService will be called?
2 Replies
Cracker
Cracker3y ago
It might be better to not use DI, just create instance within using scope if disposing is important for you. There is no other service dependency in ClientGrpcService so its easy to take it out from DI container
undisputed world champions
i guess you want to reuse the same IClientGrpcService instance across multiple other services? then you could register it as a scoped service in DI and create/dispose a scope according to your needs here is a article showing some further possibilities: https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines#disposal-of-services
Want results from more Discord servers?
Add your server