简体   繁体   中英

Autofac to inject dependency automatically using InjectProperties or manually resolve using Resolve<>

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM