0

I have a C# project that is used as part of a Visual Studio Extension.

To support earlier versions of VS, the project set to Target framework .NET Framework 3.5.

The project makes a reference to System.ServiceModel.

Depending on which version of Visual Studio is running, a different version of System.ServiceModel will be used. VS2008 will use the .NET 3.5 version DLL, while VS2012 will use the .NET 4.5 version at runtime, regardless of the project target framework.

My problem is that a Property was added to HttpTransportBindingElement in .NET 4, called DecompressionEnabled. Because I target .NET 3.5, I cannot compile with changes to this property; however, I do need to change its value.

The work around I am using to change the property at run time, is to use reflection:

public static void DisableDecompression(this HttpTransportBindingElement bindingElement)
{
 var prop = bindingElement.GetType()
                         .GetProperty("DecompressionEnabled",
                                       BindingFlags.Public | BindingFlags.Instance);
 if (null != prop && prop.CanWrite)
 {
     prop.SetValue(bindingElement, false, null);
 }
}

The solution works, but I am wondering if there is a better design pattern for handling this, without the need for reflection.

Community
  • 1
  • 1
Sheldon Warkentin
  • 1,706
  • 2
  • 14
  • 31

1 Answers1

1

See: Detect target framework version at compile time

    public static void DisableDecompression(this HttpTransportBindingElement bindingElement)
    {
#if RUNNING_ON_4
        bindingElement.DecompressionEnabled = false;
#endif
    }

Once the build is set to release for .NET 3.5 then all references to DisableDecompression will be optimized out.

Community
  • 1
  • 1
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • Unfortunately, this doesn't really solve the problem. The issue is that the referenced library can be a different version at run-time. The build is always set to 3.5, but needs to be able to use properties in the API of higher versions of a class in the referenced library. – Sheldon Warkentin Jul 31 '13 at 16:36
  • 2
    If you use that method then reflection is probably the answer. – Dustin Kingen Jul 31 '13 at 16:39
  • I think you're right @Romoku, it seems like the most workable solution. I could probably make different compilations of the project for different .NET versions... but this most likely adds much more complexity. – Sheldon Warkentin Jul 31 '13 at 18:15
  • It will add complexity, but the main difference will be different `csproj` files for each target which are just MSBuild files. Check out how [MvvmLight](http://mvvmlight.codeplex.com/SourceControl/latest) separates their builds. – Dustin Kingen Jul 31 '13 at 18:56