'Transient service in a blazor server project
I have create a Service in a blazor server project.
I have declared this way in Startup.cs:
services.AddTransient<IMyService, MyService>();
I have put some log in service constructor:
class MyService: IMyService
{
public MyService()
{
Console.WriteLine("Constructor");
}
public ~MyService()
{
Console.WriteLine("Destructor");
}
}
I am injecting this service on a blazor page:
@page "/"
@inject IMyService service
I do not understand:
- If i load one page, constructor is called 2 times.
- If i load a second page in my browser, constructor is called 2 times again. I was thinking constructor was called once per page. Why is there a second instance ?
- Destructor is NEVER called. What should i do to clean up memory ?
Thanks
Solution 1:[1]
To answer your questions:
If i load one page, constructor is called 2 times.
If this is the first page of the application in Server mode then yes it will. The server render and then the final client side render.
If i load a second page in my browser, constructor is called 2 times again. I was thinking constructor was called once per page. Why is there a second instance ?
Are you reloading the application? Two loads would suggest you are?
Destructor is NEVER called. What should i do to clean up memory ?
I think the Service container deals with objects with destructors the same as classes implementing IDispose: it hangs on to a reference to the object until the service container itself is destroyed. Thus the GC doesn't destroy any transient objects till the Scoped service container is destroyed by the GC.
You need to look at OwningComponentBase to deal with transient services that need destructors/implement IDispose. The service container gets destroyed when the component goes out of scope This is a common memory leak issue with DbContexts and transient services.
Can anyone definitively confirm/refute this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MrC aka Shaun Curtis |
