0

I have a Logging project (class library) that is referenced by other projects.

When the Logging library is first loaded, I want it to run a method to confirm that directories exist, and if not, create them.

I have tried creating a Main method in the Logging project, but this doesn't trigger.

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
Dan Pettis
  • 113
  • 5
  • 1
    You don't load projects, you load assemblies. I assume you are talking about a class library? – Klaus Gütter Jul 24 '20 at 07:19
  • yes @KlausGütter class library – Dan Pettis Jul 24 '20 at 07:21
  • Then there is no `Main`. Could you add the code to a constructor of some "central object" in your library? It all depends on how the API of the library is structured. – Klaus Gütter Jul 24 '20 at 07:26
  • A static constructor should do. Assuming you have single class in assembly or all classes are dependent on the one with constructor, or all classes have static constructors. [Related](https://stackoverflow.com/q/505237/1997232) – Sinatr Jul 24 '20 at 07:29

1 Answers1

-1

The answer was to add a static constructor.

public static class Hello
{
    static Hello() {
    }
}
Dan Pettis
  • 113
  • 5
  • 3
    Well, @DanPettis there is a subtlety; a static constructor is not invoked when it's containing assembly is loaded - it's invoked the first time code needing the type it is jitted, which may or may not be a problem depending on your scenario. – James World Jul 24 '20 at 07:36
  • Also, you might have a hard time finding errors if the code in the type initializer throws an exception (which is not unlikely if you are dealing with I/O). – Klaus Gütter Jul 24 '20 at 08:42