C# 类构造函数方法中与IoC的代码契约
我是代码合同方面的新手,我有一个关于如何将其与IoC集成的问题。 我曾尝试在简单测试程序(经典的Console项目)中使用代码契约,但现在我想在我的正式项目中使用它。 问题是:如果我有一个在类的构造函数方法中提供服务接口的容器,我如何使用代码契约来检查传递的值 经典的情况可能是C# 类构造函数方法中与IoC的代码契约,c#,constructor,ioc-container,code-contracts,C#,Constructor,Ioc Container,Code Contracts,我是代码合同方面的新手,我有一个关于如何将其与IoC集成的问题。 我曾尝试在简单测试程序(经典的Console项目)中使用代码契约,但现在我想在我的正式项目中使用它。 问题是:如果我有一个在类的构造函数方法中提供服务接口的容器,我如何使用代码契约来检查传递的值 经典的情况可能是 [ContractClass(typeof(ArticoliBLLContract))] public interfare IMyInterface { void method1(int a) void method
[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;
}
}
[ContractClass(typeof(ArticoliBLLContract))]
公共接口
{
无效方法1(int a)
无效方法2(字符串b)
无效方法3(布尔c)
}
[ContractClassFor(typeof(iarticolibl))]
公共抽象类MyContractsClass:IMyInterface
{
公共无效方法1(int a)
{
合同要求(a>0,“a必须大于0”);
}
公共无效方法2(字符串b)
{
Contract.Requires(!String.IsNullOrEmpty(b),“b不能为空”);
}
公共作废方法3(bool c)
{
要求(c==true,“c必须为true”);
}
}
公共类MyClass:IMyInterface
{
私有ITFactory _factory=null;
private IMyDAL _myDAL=null;
公共MyClass(ITFactory工厂,IMyDAL myDAL)
{
如果(工厂==null)
抛出新的异常(“工厂”);
如果(myDAL==null)
抛出新的异常(“myDAL”);
_工厂=工厂;
_myDAL=myDAL;
}
公共无效方法1(int a)
{
a=a*2;
}
公共无效方法2(字符串b)
{
b=b+“方法2”;
}
公共作废方法3(bool c)
{
c=假;
}
}
在这个场景中,我在哪里可以检查“工厂”和“myDAL”?
有没有一种方法可以将契约放在抽象类中以保持它在同一个类中
谢谢你 构造函数参数的要求是特定于特定实现的——就像构造函数本身不是继承的一样,它们所需的参数也不是继承的
我通常会在构造函数中将它们表示为契约,但仅此而已——它们不应该是抽象类契约集的一部分。(考虑另一个具体的子类,它实现了这些方法,但根本不使用这些参数。这是一个完全合理的方案,没有什么会因为没有这些值而失败。)谢谢!我将尝试使用子类!