I need to expose a singleton shared object across all controllers/action methods in Asp.Net WebAPI. Which is the best place to declare such global static objects so that all co
You can use Lazy. This will ensure thread safety:
public class Greeter
{
public static readonly Lazy Instance = new Lazy(() => new Greeter());
public Greeter()
{
// I am called once during the applications lifetime
}
public string Greet(string name)
{
return $"Hello {name}!";
}
}
Then use this wherever you like:
public class GreetController : ApiController
{
public IHttpActionResult Get(string name)
{
var message = Greeter.Instance.Value.Greet(name);
return Ok(message);
}
}