Global static object shared across all API Controllers/action methods

前端 未结 3 858
無奈伤痛
無奈伤痛 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:11

    You can declare variable inside your WebApiApplication (Global.asax.cs) and use it in all controllers with code:

    var globalValue = (HttpContext.Current.ApplicationInstance as WebApiApplication).GlobalVariableName;
    

    But as for me it's not the best way, because you'll get overhead with initialization and setting value and also it looks like some architecture issue.

    Why do you need global object? If it some function just declare new parent controller and declare this function in it. If you need read only data - put it into web.cofig.

提交回复
热议问题