Yesterday I blogged about an issue I had with Telerik. I needed to initialize some code before I could call the PDF conversion functionality:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Telerik.Windows.Documents.Extensibility.JpegImageConverterBase jpegImageConverter = new Telerik.Documents.ImageUtils.JpegImageConverter(); | |
Telerik.Windows.Documents.Extensibility.FixedExtensibilityManager.JpegImageConverter = jpegImageConverter; |
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.CompilerServices; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace Example | |
{ | |
class Initializer | |
{ | |
[ModuleInitializer] | |
public static void Init() | |
{ | |
//Add your logic here | |
} | |
} | |
} |