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
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.