2

I'm using Autofac in ASP.Net WebForm. According to the documentation, if I want to resolve dependencies in web controls, I'll need to use the following approach -

Dependency Injection via Base Page Class

public class MyWebControl : WebControl
{
   public IFirstService FirstService { get; set; }
   public ISecondService SecondService { get; set; }

   public MyWebControl()
   {        
      var cpa = (IContainerProviderAccessor)
           HttpContext.Current.ApplicationInstance;
      var cp = cpa.ContainerProvider;
      cp.RequestLifetime.InjectProperties(this);
   }
}

The above code work fine. However, in order to improve the speed, I'm thinking that I can resolve depedencies myself using the following approach.

public MyWebControl()
{        
   var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
   var cp = cpa.ContainerProvider;
   FirstService = cp.ApplicationContainer.Resolve<IFirstService>();
   SecondService = cp.ApplicationContainer.Resolve<ISecondService>();
}

Please correct me if I'm wrong. I doubt that it is a Service Locator pattern (Mark Seemann said Service Locator is an Anti-Pattern in Dependency Injection in .NET book).

Question

Should I use the first approach or second?

Win
  • 61,100
  • 13
  • 102
  • 181

1 Answers1

2

I'd say use the first approach. The least knowledge your code has on the actual container the better. You should only care about your dependencies.

atomaras
  • 2,468
  • 2
  • 19
  • 28
  • In what way the code has more knowledge of the container in the second example? Both code samples depend on Autofac and they both depend on the same amount of API entry points. – Steven Nov 08 '13 at 08:27
  • @Steven Those were they only options given. The first one is one step closer to ideal. If i had my way with it i'd use Constructor Injection. – atomaras Nov 08 '13 at 08:32
  • I agree, it's far from ideal. Unfortunately constructor injection is [not easy in web forms](http://stackoverflow.com/questions/6504150/why-does-everyone-say-dependency-injection-in-asp-net-webforms-is-hard-when-page) which is a shame. – Steven Nov 08 '13 at 08:43
  • @atomaras As far as I know, constructor Injection cannot be used in ASP.Net WebControl. If you have a better method, please kindly post it. I'm willing to change my code. – Win Nov 11 '13 at 04:12