Domanda

Question background:

I currently have a couple of 'Random' number instances in my code - used in two classes - where I need to append a randomly generated number to the name of some folders I am creating. Once the work - in this case mapping files to these new folders - is done they're immediately deleted.

Code:

I have two private static instances of the following code in each of the mentioned classes:

private static randomNo = new Random((int)DateTime.Now.Ticks);

Singleton? Or two static instances?:

So far I have not run into any duplication issues. I still feel that I should be developing a singleton to share a single static random number object instance over my whole solution.

I am using IoC (Unity) to create all of my classes and am not sure how I should go about handling sharing the static Random instance? Can I 'new' the singleton class up in each class that requires it? Or will this cause the static Random instance to reset? Do I need to create one singleton class and pass it between the classes requiring a randomly generated number?

I should mention I do have checks in place to ensure that when a new folder name is created with a random number appended to it, I ensure the name doesn't already exist.

È stato utile?

Soluzione

You don't strictly need to use a Random singleton throughout your application. Most of the time (including in this case) using more than one instance is a sign of preferring convenience over "theoretical correctness", but there are legitimate cases where different program components use different RNGs by design so that the behavior of each component over the lifetime of the program is deterministic.

If you want to move to a singleton instance you should use RegisterType to instruct the container that it should satisfy all requests for a Random object with the same instance:

container.RegisterType<Random>(new ContainerControlledLifetimeManager());

This will not create a Random instance on the spot; instead, it will instruct the container that once a request for Random has been resolved, subsequent requests will be resolved with that same instance.

After that, it's just a matter of resolving the singleton instance with container.Resolve<Random>() or making the dependency visible to the container so that it automatically resolves and injects the RNG instance when you instruct it to resolve one of the RNG's users.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top