Issue with ref keyword in EntLib 5.0

Topics: Enterprise Library Core
Oct 29, 2013 at 1:08 PM
I am trying to host my Wcf service with Entlib 5.0 Validation. When servie operation contracts go for validation they get crash. Whiel investigating, I found that ref keyword in Wcf service's operation giving this problem. E.g.:

Operation contract in service is like:

public void GetData(int ID, string name, ref string location) {};

Now, while validating string location, it gets crash and if I remove ref keyword it works fine.

Though, in EntLib version 4.0 there are no such issues.

Can anybody help me on this?

Thanks in advance.
Oct 30, 2013 at 7:03 AM
The issue is that when a ref parameter is used with WCF the ParameterInfo type is not what is expected by the Validation Application Block.

Usually the Type (based on the GetData method above) would be System.String. But because it is a ref parameter the Type is System.String&. This causes an issue in the ValidatorFactory when trying to create a generic type of System.String&. I see an ArgumentException with a message of "The type 'System.String&' may not be used as a type argument."

The error occurs in ValidatorFactory.cs in the WrapAndInstrumentValidator method:
var validatorWrapperType = typeof(GenericValidatorWrapper<>).MakeGenericType(type);
One solution would be to modify the code in ValidatorFactory.cs to use the result of GetElementType() as the type if the value is not null:
protected virtual Validator WrapAndInstrumentValidator(Validator validator, Type type)
    // New check
    Type underlyingType = type.GetElementType() ?? type;

    var validatorWrapperType = typeof(GenericValidatorWrapper<>).MakeGenericType(underlyingType);
    var validatorWrapper = (Validator)Activator.CreateInstance(
        new object[] { validator, InstrumentationProvider });

    return validatorWrapper;

This works for me and unit tests still seem happy.

Unfortunately, this means modifying Enterprise Library source code, rebuilding and using a custom build.

An alternative would be not to use ref with WCF services and instead use request/response objects that contain multiple properties if you need to return multiple values. In my experience, this is a more common approach than using ref parameters with WCF.

Randy Levy
Enterprise Library support engineer
Support How-to
Oct 30, 2013 at 1:14 PM
Thanks Randy.
Feb 5, 2015 at 8:23 AM
Is this solution ( type.GetElementType()... ) fixed in MSE 6.0? Or, do we still need to modify the library code again and do the same as it is for MSE 5.0?

Inother words, does MSE 6.0 has intelligence to identify 'ref' parameter?

Please help me.

Thanks in advance for your help.

Pradeep Daram
Feb 5, 2015 at 9:46 AM
Let me check

Sent from my iPhone