Yesterday I blogged about an issue I had with Telerik. I needed to initialize some code before I could call the PDF conversion functionality:
The question is where should I put this logic?
Perfect case to try out a new C# 9 feature: Module initializers.
Module initializers allow you to do eager, one-time initialization when a module is loaded, with minimal overhead and without the user needing to explicitly call anything.
Creating a module initializer is easy. Just add the ModuleInitializerAttribute
on top of a method. Some requirements are imposed on the method targeted with this attribute:
- The method must be
static
. - The method must be parameterless.
- The method must return
void
. - The method must not be generic or be contained in a generic type.
- The method must be accessible from the containing module.