Question

This one has me stumped. I am using Code Contracts in a scenario where methods to which the contracts apply are interface implementations. So, I am using the abstract ContractClassFor approach to define the contract requirements. This works fine for one of the implementing classes (it happens to be in the same project as the interface), but contracts are never applied to the second implementation (which is in a separate project). Both projects have the same Code Contract settings (Standard Contract Requires; Full runtime contract checking). Here is the scenario in code:

namespace First.Interfaces {
    [ContractClass(typeof(ContractForIMyClass))]
    public interface IMyClass {
        void MyMethod(int id);
    }

    [ContractClassFor(typeof(IMyClass))]
    public abstract class ContractForIMyClass : IMyClass
    {
        void MyMethod(int id) {
            Contract.Requires<ArgumentException>(id != 0);
        }
    }
}

namespace First {
    public class MyClass : IMyClass {
        public void MyMethod(int id) {
            //contract is applied here
        }
    }
}

namespace Second {
    public class MyTestClass : IMyClass {
        public void MyMethod(int id) {
            //contract is not applied
        }
    }
}

Any thoughts where to look much appreciated.

Was it helpful?

Solution

You'll need to do two things for this to work:

  1. Build a contract reference assembly for the assembly that contains the interface.
  2. Consume that contract reference assembly when building the project containing the second class.

Both options can be controlled from the Code Contracts section in the properties pages of the respective projects in Visual Studio. (If you're using standard project references within a single solution, you probably won't have to do anything for #2 once you've fixed #1.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top