Search code examples
c#asp.net-corerazorrazorengineasp.net-core-8

Is ASP.NET Core 8 HtmlRenderer thread-safe?


Background: It looks like a new class was added to ASP.NET Core 8, HtmlRenderer, which allows rendering CSHTML to a string beyond the standard use case of rendering cshtml via a request/response. An example I've found show using this to render CSHTML to a string in a console application:

https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-components-outside-of-aspnetcore?view=aspnetcore-8.0

but I'd like to actually use this within an ASP.NET Core 8 controller (to render the text of an email) where I am currently using dependency injection. Accordingly, I'd like to understand if HtmlRenderer is thread-safe as that should inform how I move forward (if I register its wrapper as a singleton or as scoped in the DI container).

Thanks...


Solution

  • You should assume objects are not thread safe, unless otherwise documented.

    The documentation for HtmlRenderer mentions the following for the dispatcher property:

    Gets the Dispatcher associated with this instance. Any calls to RenderComponentAsync<TComponent>() or BeginRenderingComponent<TComponent>() must be performed using this Dispatcher.

    So no, calls to these methods cannot be done from an arbitrary thread. Only from the thread associated with the dispatcher.

    It is not clear to me what rules apply for Dispose and DisposeAsync.