Global static object shared across all API Controllers/action methods

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

    The "best" way is to use a DI (dependency injection) container, and inject the singleton into the controllers that need it. I'll give an example with Ninject, since that's what I use, but you can easily adapt the code to whatever container you decide on.

    NinjectWebCommon.cs

    kernel.Bind().ToSelf().InSingletonScope();
    

    Controller(s)

    public class FooController : ApiController
    {
        protected readonly MySingleton mySingleton;
    
        public FooController(MySingleton mySingleton)
        {
            this.mySingleton = mySingleton;
        }
    }
    

    In other words, the DI container manages the singleton. Your controller(s) accept the singleton as a constructor param, and set it on the controller. The DI container will then inject the singleton into the controller, and you can then use it freely as you would any other member of the controller.

提交回复
热议问题