Autofac to inject dependency automatically using InjectProperties or manually resolve using Resolve<>
我在ASP.Net WebForm中使用Autofac。 根据文档,如果我想解决Web控件中的依赖项,则需要使用以下方法-
通过基页类进行依赖注入
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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); } } |
上面的代码工作正常。 但是,为了提高速度,我认为我可以使用以下方法自己解决问题。
1 2 3 4 5 6 7 | public MyWebControl() { var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance; var cp = cpa.ContainerProvider; FirstService = cp.ApplicationContainer.Resolve<IFirstService>(); SecondService = cp.ApplicationContainer.Resolve<ISecondService>(); } |
如果我错了,请纠正我。 我怀疑这是一种服务定位器模式(Mark Seemann说服务定位器是.NET书中的依赖注入的反模式)。
题
我应该使用第一种方法还是第二种方法?
我会说使用第一种方法。 您的代码对实际容器了解的越少越好。 您应该只关心您的依赖项。