Random number generation in MVC applications

Posted by SlimShaggy on Stack Overflow See other posts from Stack Overflow or by SlimShaggy
Published on 2010-05-17T07:41:52Z Indexed on 2010/05/17 7:50 UTC
Read the original article Hit count: 217

What is the correct way of generating random numbers in an ASP.NET MVC application if I need exactly one number per request? According to MSDN, in order to get randomness of sufficient quality, it is necessary to generate multiple numbers using a single System.Random object, created once. Since a new instance of a controller class is created for each request in MVC, I cannot use a private field initialized in the controller's constructor for the Random object. So in what part of the MVC app should I create and store the Random object? Currently I store it in a static field of the controller class and lazily initialize it in the action method that uses it:

public class HomeController : Controller
{
    ...

    private static Random random;

    ...

    public ActionResult Download()
    {
        ...

        if (random == null)
            random = new Random();

        ...

    }
}

Since the "random" field can be accessed by multiple instances of the controller class, is it possible for its value to become corrupted if two instances attempt to initialize it simultaneously? And one more question: I know that the lifetime of statics is the lifetime of the application, but in case of an MVC app what is it? Is it from IIS startup till IIS shutdown?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about random