类构造方法中与IoC的代码契约

Fab*_*ber 3 c# constructor ioc-container code-contracts

我是Code Contracts的新手,我对如何将它与IoC集成提出了疑问.我试图在简单的测试程序(经典的consolle项目)中使用Code Contracts,但现在我想在我的官方项目中使用它.问题是:如果我有一个容器在类的构造函数方法中提供我的服务接口,我如何使用代码约定来检查传递的值?

经典场景可能是

[ContractClass(typeof(ArticoliBLLContract))]
public interfare IMyInterface
{
 void method1(int a)
 void method2(string b)
 void method3(bool c)
}


[ContractClassFor(typeof(IArticoliBLL))]
public abstract class MyContractsClass : IMyInterface
{

 public void method1(int a)
 {
  Contract.Requires<ArgumentOutOfRangeException>(a > 0,"a must be > 0");                                                    
 }

 public void method2(string b)
 {
  Contract.Requires<ArgumentOutOfRangeException>(!String.IsNullOrEmpty(b),"b must be not empty");                                    
 }

 public void method3(bool c)
 {
  Contract.Requires<ArgumentOutOfRangeException>(c == true,"c must be true");                                    
 }
}


 public class MyClass : IMyInterface
 {
  private ITFactory _factory = null;
  private IMyDAL _myDAL = null;

  public MyClass(ITFactory factory,IMyDAL myDAL)
  {
    if (factory == null)
      throw new ArgumentNullException("factory");

    if (myDAL == null)
      throw new ArgumentNullException("myDAL");

    _factory = factory; 
    _myDAL = myDAL;
  }

  public void method1(int a)
  {
    a = a*2;
  }

  public void method2(string b)
  {
    b = b + "method2";
  }

  public void method3(bool c)
  {
    c = false;
  } 
 }
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我在哪里可以检查"工厂"和"myDAL"?有没有办法将合同放在抽象类中以使其保持在同一个类中?

谢谢!!!

Jon*_*eet 5

构造函数参数的要求特定于特定实现 - 就像构造函数本身不是继承的那样,它们的必需参数不是.

我会在构造函数中将它们表示为正常的契约,但这就是全部 - 它们不应该是抽象类集合的一部分.(考虑另一个实现方法而不使用这些参数的具体子类.这是一个完全合理的场景,没有任何东西因为你没有这些值而失败.)