0

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

Community
  • 1
  • 1
acostela
  • 2,597
  • 3
  • 33
  • 50
  • 2
    While you can limit the disadvantages of a Singleton with `Lazy`, a good DI container can give you much better control over the object's lifetime and implement, eg object per request, singleton or always new. The downside can be a performance hit if there are a *lot* of requests and configured types, but good DI containers take care to cache type information and speed up lookups. – Panagiotis Kanavos Jun 20 '16 at 16:05
  • @PanagiotisKanavos So if we won't have a big amount of requests, DI will be safer and less error prone? – acostela Jun 20 '16 at 16:14
  • 1
    Having the controller reach out to a central location and request a specific implementation is commonly called the _Service Locator_ pattern - and some would call it an anti-pattern. When you have to change a dependency for a range of classes (rather than a single, specific class), you will have to manually chase down all of the dependencies rather than having a single location where dependencies are set. A Dependency Injection _Container_ such as Ninject may serve you better in the long term. – Max Jun 20 '16 at 19:58

0 Answers0