Search code examples
c#wpfdata-binding.net-core-3.0.net-standard-2.1

Missing interface in .net standard


I am trying to implement port a class to my .net standard 2.1 library. That class implements ICustomTypeProvider so that WPF can bind to some dynamic properties. That interface is not available in .net standard. I understand why this interface isn't there, but it's a simple interface to recreate on my own. My question is: if I did recreate this interface in my .net standard library, then would there be a way that when I consumed that class in my WPF library, that it could be recognized as the predefined ICustomTypeProvider without the need of creating a wrapper class around it? If I need to go the wrapper route that's cool, I was just wondering if I'm missing a cleaner way to implement this, but I didn't find anything. Thanks for any insight.


Solution

  • You can recreate the interface yourself but it will not be used by the WPF framework.

    However this interface is available in net core 3. You could target that instead of netstandard. If you need to produce a netstandard version I suggest you to use multitargeting between netcore and net standard, and only implement ICustomTypeProvider in net core (with #IF xxx). See below :

    Project.csproj

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFrameworks>netstandard2.0;netstandard2.1;netcoreapp3.0</TargetFrameworks>
      </PropertyGroup>
    
    </Project>
    

    Class1.cs

    using System;
    
    namespace lib
    {
        public class Class1
    #if NETCOREAPP3_0
        : System.Reflection.ICustomTypeProvider
    #endif
        {
            public Type GetCustomType()
            {
    #if !NETCOREAPP3_0
                throw new NotSupportedException();
    #else
                return this.GetType(); // return your impl
    #endif
            }
        }
    }
    

    In this case, on not netcoreapp3.0 target the interface will not exist. If you need it add it like that and remove previous #if lines:

    #if !NETCOREAPP3_0
    namespace System.Reflection
    {
        public interface ICustomTypeProvider
        {
            Type GetCustomType ();
        }
    }
    #endif
    

    See https://learn.microsoft.com/en-us/dotnet/standard/frameworks for list of preprocessor symbols