I would like to add a Contract.Requires to every method in my code that has a parameter of a certain type. How would I achieve this?
Consider the following trivialized example:
public class ValuesController : ApiController
{
public string Get(int id)
{
return GetValue(id);
}
private string GetValue(int id)
{
Contract.Requires(HttpContext.Current.Request.Headers["key"] != null);
return id.ToString();
}
}
How could I change that to work like:
public class ValuesController : ApiController
{
public string Get(int id)
{
return GetValue(id);
}
[AddContract]
private string GetValue(int id)
{
return id.ToString();
}
}
Where I can then multicast the AddContract attribute.
I considered using PostSharp, but it didn't seem to work. I think this might be to do with PostSharp's IL weaving not playing nicely with the metadata created by the code contracts, but my knowledge is lacking in that area.
My attempt looked something like this:
public class ValuesController : ApiController
{
public string Get(int id)
{
return GetValue(id);
}
[AddContract]
private string GetValue(int id)
{
return id.ToString();
}
}
[Serializable]
public class AddContract : MethodInterceptionAspect
{
public override void OnInvoke(MethodInterceptionArgs args)
{
Contract.Requires(HttpContext.Current.Request.Headers["key"] != null);
args.Proceed();
}
}
But did not work - the static code analysis does not recognize the contract.