We are designing a webApi in Asp.Net and we achieved two differents design patterns and I have some doubts about them.
The first approach is to have an static object of the controller that we instantiate and use, when we instantiate it we initialize all the dependencies that this controller has.
public class SingletonController: ApiController
{
private static SingletonController m_singleton;
public SingletonController()
{
if(m_singleton == null)
{
m_controllerDependency = Startup.DependenciesContainer.Get<MyDependency>();
if(m_controllerDependency != null)
{
//Subscribe events and code in relation with dependencies
m_singleton = this;
}
}
}
}
Personally, I don't like this approach. We are maintaining constantly an instance of an object after the first request arrives. It's dangerous because we can create some temporary objects that maintains between different requests and maybe this is not what we want. Furthermore, I don't know which behavior I will obtain if we have two simultaneous requests. I Suppose that in this case I must control the concurrency using lockers.
Second approach is using Dependency injection wrapping my DependenciesContainer class as described here http://www.asp.net/web-api/overview/advanced/dependency-injection
In this case we create our controller in each request and we don't need a singleton pattern. I know that the previously commented cons will be avoided but I don't know if we have a big cons using this pattern or something that I must have into account.
Thank you very much.
EDIT: I read this SO thread but I still have these doubts ASP.NET Web Api Dependency Injection - Singleton or not