【问题标题】:Autofac to inject dependency automatically using InjectProperties or manually resolve using Resolve<>Autofac 使用 InjectProperties 自动注入依赖项或使用 Resolve<> 手动解析
【发布时间】: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


    【解决方案1】:

    我会说使用第一种方法。您的代码对实际容器的了解越少越好。你应该只关心你的依赖关系。

    【讨论】:

    • 第二个例子中的代码如何对容器有更多的了解?两个代码示例都依赖于 Autofac,并且它们都依赖于相同数量的 API 入口点。
    • @Steven 这些是他们唯一的选择。第一个是离理想更近一步。如果我有办法,我会使用构造函数注入。
    • 我同意,这远非理想。不幸的是构造函数注入是not easy in web forms,这很可惜。
    • @atomaras 据我所知,构造函数注入不能在 ASP.Net WebControl 中使用。如果您有更好的方法,请发布。我愿意更改我的代码。
    猜你喜欢
    • 2016-11-09
    • 1970-01-01
    • 2018-06-04
    • 2014-09-12
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多