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?