Global static object shared across all API Controllers/action methods

前端 未结 3 893
無奈伤痛
無奈伤痛 2021-01-27 01:33

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

3条回答
  •  庸人自扰
    2021-01-27 02:24

    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);
        }
    } 
    

提交回复
热议问题