mercredi 5 février 2020

Hygienic way of sharing one Random in entire application

If you use System.Random all over the place, is there a hygienic way of making sure that it's an app-wide singleton? I've though of several options, including the following:

  • Global static member -- this has the unfortunate effect of having to call SomeClass.Random.Next(). This can be mitigated with using static but the approach doesn't really scale since you have to do this everywhere.
  • Derived singleton -- simply deriving from Random (it's not sealed!) and making that class a lazy thread-safe singleton
  • Register a random in DI as a singleton and inject -- but injecting a Random into every class is really tedious

Ideally I just want to call some rand() in any class and have all of them refer to a single instance.




Aucun commentaire:

Enregistrer un commentaire