Create Delegate throws a binding error due to signature or security transparency

850 views Asked by At

I am using C#4.0 and .NET 4.5.

I have this class which is the point of entry in the current context:

public static class HttpConfigurationImporter
        {
            public static readonly string ConfigurationMethodName = "Register";
            public static readonly string ConfigClassName = "WebApiConfig";
            public static readonly string HelpPageConfigClassName = "HelpPageConfig";

            public static HttpConfiguration ImportConfiguration(string assemblyPath)
            {
                var assembly = Assembly.LoadFrom(assemblyPath);

                string originalDirectory = Environment.CurrentDirectory;
                Environment.CurrentDirectory = Path.GetDirectoryName(assemblyPath);

                Type webApiConfigType = assembly
                                  .GetTypes()
                                  .FirstOrDefault(t => t.Name == ConfigClassName);

                MethodInfo registerConfigMethod = webApiConfigType
                    .GetMethod(ConfigurationMethodName
                    , BindingFlags.Static | BindingFlags.Public);

                  //ERROR on this LINE
                  Action<HttpConfiguration> registerConfig = Delegate.
                    CreateDelegate(typeof(Action<HttpConfiguration>), 
                    registerConfigMethod)
                    as Action<HttpConfiguration>;

                HttpConfiguration config = new HttpConfiguration();
                registerConfig(config);
                ImportHelpPageConfiguration(assembly, config);
                Environment.CurrentDirectory = originalDirectory;
                return config;
            }
     }

And when I try to create the delegate for this following target in another assembly..:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration configuration)
        {
            configuration.MapHttpAttributeRoutes();
        }
    }

I get the error: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

How to resolve this?

1

There are 1 answers

0
David B. On

Delete this part:

//ERROR on this LINE
Action<HttpConfiguration> registerConfig = Delegate.
                    CreateDelegate(typeof(Action<HttpConfiguration>), 
                    registerConfigMethod)
                    as Action<HttpConfiguration>;

– and try to invoke the Register method this way

registerConfigMethod.Invoke(new object(), new object[] { config });

– instead of

registerConfig(config);

it's going to return a more accurate error like in my case:

System.ArgumentException: 'Object of type 'System.Web.Http.HttpConfiguration' cannot be converted to type 'System.Web.Http.HttpConfiguration'.'

where I had a different versions system.web.http.dll for built assembly and for assembly where I executed this code