ASP.Net WebForm で Autofac を使用しています。ドキュメントによると、Web コントロールの依存関係を解決したい場合は、次のアプローチを使用する必要があります -
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);
}
}
上記のコードは正常に動作します。しかし、速度を向上させるために、次のアプローチを使用して依存関係を自分で解決できると考えています。
public MyWebControl()
{
var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
FirstService = cp.ApplicationContainer.Resolve<IFirstService>();
SecondService = cp.ApplicationContainer.Resolve<ISecondService>();
}
私が間違っている場合は、私を修正してください。それが Service Locator パターンであるとは思えません(Mark Seemann は Service Locator is an Anti-Pattern in Dependency Injection in .NET bookと述べています)。
質問
最初のアプローチと 2 番目のアプローチのどちらを使用する必要がありますか?