【发布时间】:2013-11-08 00:48:04
【问题描述】:
我在 ASP.Net WebForm 中使用 Autofac。根据文档,如果我想解决 web 控件中的依赖关系,我需要使用以下方法 -
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);
}
}
上面的代码工作正常。但是,为了提高速度,我想我可以使用以下方法自己解决依赖关系。
public MyWebControl()
{
var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
FirstService = cp.ApplicationContainer.Resolve<IFirstService>();
SecondService = cp.ApplicationContainer.Resolve<ISecondService>();
}
如果我错了,请纠正我。我怀疑它是一个服务定位器模式(Mark Seemann 在Dependency Injection in .NET book 中说服务定位器是一个反模式)。
问题
我应该使用第一种方法还是第二种方法?
【问题讨论】:
标签: c# asp.net dependency-injection autofac