Property Injection over Constructor Injection有什么优势吗?

时间:2012-05-06 14:01:58

标签: .net code-injection constructor-injection property-injection

  

可能重复:
  Dependency injection through constructors or property setters?

如果 Property Injection 构造函数注入有任何优势,我很好奇:

  public class LoginController : Controller
  {
    [Inject]
    public ICookiesManager CookiesManager {get; set;}

    [Inject]
    public ISecurityManager SecurityManager {get; set;}

    public LoginController()
    {

    }
  }

VS

  public class LoginController : Controller
  {
    private ICookiesManager _cookiesManager;
    private ISecurityManager _securityManager;

    public LoginController(ICookiesManager cookiesManager, ISecurityManager securityManager)
    {
      _securityManager = securityManager;
      _cookiesManager = cookiesManager;
    }
  }

1 个答案:

答案 0 :(得分:1)

除了属性注入之外,两种模式的有效差异非常小,您可以使用简单的属性集替换实现。使用构造函数注入时,通常会更明确地表示您不希望任何人在运行时替换实现(因为这样做需要创建一个新的LoginController。)