Global instance of a class or static class with initialization method

I have a class that handles the Localization of my application. My goal is that the class can be used throughout the application, so I made it static. This allows me to name the code below anywhere in my application.

Localizer.GetString(/* Key to localize */) 

The method uses several fields in the Localizer class. To ensure that these fields are set, the Init method has been added to initialize Localizer. If a user of my class forgets to call Init , for example, when starting the application, exceptions will occur because the fields are not set.

One solution that I think of making the Localizer class non-static, adds a constructor that sets the fields and initializes the class in the global static class in my application, something like this:

 public static class Globals { public static Localizer Localize = new Localizer(/* Field arguments here */); } 

Now I'm not sure which is the best approach. Or

  • A static localizer, but the user must ensure that Init is called before using the class.
  • Installed localizer in the global static class in the application.

One more note: the user does not have access to the class source.

+7
c #
source share
1 answer

An alternative to what you do would be to use dependency injection . Including dependencies is a super bizarre name for passing stuff into things, not for those who directly access this stuff . I know this vague statement, but if your class takes an argument for the field instead of creating the type itself, it already uses dependency injection.

So let's say you have a Localizer class. It has no static methods, and a static instance of a localizer is not global.

By creating a Localizer instance specialized for your needs, once when the application loads:

 var localizer = new Localizer(...); 

Then, when the component needs a localizer - you pass it

 var component = new MyComponent(localizer); // we pass the values in 

This makes the localizer easily modifiable, makes it easy to test classes, and makes it easy to configure different components in different ways (what if you want the help page to always be in English all of a sudden? Or some other specific page?).

If it’s still unclear, here is Mishko Heavy’s good talk about not looking for things . There is also a good article by Martin Fowler , but perhaps this is a bit more complicated.

The only tedious thing is that you need to transfer it at any time. I am not opposed to the explanation, but many people prefer to use dependency injection containers to manage overhead.

+4
source share

All Articles