question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Regression: InvalidCastException while creating a WCF channel in Azure Function

See original GitHub issue

Investigative information

Please provide the following:

  • Function App version: v3 (“Microsoft.NET.Sdk.Functions” Version>=“3.0.6”)
  • Region: West Europe

Repro steps

Provide the steps required to reproduce the problem:

  1. Add package “System.ServiceModel.Http” Version>=“4.7.0”
  2. Create a simple HttpTrigger with the code consuming any WCF service with httpBinding:
        [FunctionName("WcfCheckHttpTrigger")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "WcfCheck")] HttpRequest req, ILogger log)
        {
            var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            var address = new EndpointAddress("https://anywcfservice.com/SimpleWcfService.svc");
            using var channelFactory = new ChannelFactory<ISimpleServiceChannel>(binding, address);

            using var channel = channelFactory.CreateChannel();
            var response = await channel.InvokeSomeServiceOperationAsync();
            return new OkObjectResult(new { Response = response });
        }
  1. Debug the function locally using Visual Studio.
  2. Deploy the function to Azure (we deploy to ASE) and invoke the trigger twice.

Expected behavior

Function invokes the WCF service successfully twice while debugging locally. Deployed Function invokes the WCF service successfully twice.

Actual behavior

Function invokes the WCF service successfully twice while debugging locally. Deployed Function invoked the WCF service successfully twice before some changes were made to the host. I don’t have exact date, but I’m sure that it was working a couple of months ago. But current behavior for deployed function is that the first invocation works as expected, but there’s an exception on a second invocation:

Exception while executing function: WcfCheckHttpTrigger 
 System.InvalidCastException : Unable to cast object of type 'generatedProxy_2' to type 'SimpleService.ISimpleServiceChannel'.
   at System.Reflection.DispatchProxy.Create[T,TProxy]()
   at System.ServiceModel.Channels.ServiceChannelProxy.CreateProxy[TChannel](MessageDirection direction,ServiceChannel serviceChannel)
   at System.ServiceModel.Channels.ServiceChannelFactory.CreateProxy[TChannel](MessageDirection direction,ServiceChannel serviceChannel)
   at System.ServiceModel.Channels.ServiceChannelFactory.CreateChannel[TChannel](EndpointAddress address,Uri via)
   at System.ServiceModel.ChannelFactory`1.CreateChannel(EndpointAddress address,Uri via)
   at System.ServiceModel.ChannelFactory`1.CreateChannel()
   at async Function.WcfCheckHttpTrigger.Run(HttpRequest req,ILogger log) at D:\a\1\s\src\Function\WcfCheckHttpTrigger.cs : 166
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync[TReflected,TReturnValue](Object instance,Object[] arguments) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs : 52
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeWithTimeoutAsync(IFunctionInvoker invoker,ParameterHelper parameterHelper,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs : 559
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstanceEx instance,ParameterHelper parameterHelper,ILogger logger,CancellationTokenSource functionCancellationTokenSource) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs : 505
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance,FunctionStartedMessage message,FunctionInstanceLogEntry instanceLogEntry,ParameterHelper parameterHelper,ILogger logger,CancellationToken cancellationToken) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs : 283
   End of inner exception
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance,FunctionStartedMessage message,FunctionInstanceLogEntry instanceLogEntry,ParameterHelper parameterHelper,ILogger logger,CancellationToken cancellationToken) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs : 330
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsync(IFunctionInstance functionInstance,CancellationToken cancellationToken) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs : 94

Known workarounds

Force runtime of one of the previous versions, that are still available (see comments for details), e. g. FUNCTIONS_EXTENSION_VERSION = ~3.0.14916. The problem is that previous versions are removed regularly. Switching to the function v2 also helps.

Related information

Provide any related information

  • Programming language used: C#
  • I found an issue with similar symptoms: https://github.com/natemcmaster/DotNetCorePlugins/issues/124 So the issue might be related to the way how function assemblies are loaded.
  • I did some other investigations related to the hosting and loading area and found out that having a static variable in the trigger similar to private static object _obj = new object() combined with code logging the hash code of that object in the trigger shows the difference in hosting models for functions running locally (the hash is the same for all function trigger invocations) and deployed function (each invocation logged different hash)

Again, important thing is that is regression issue which breaks the code, that was running for months.

P.S. Example above is very simplified version of the real code, running on production. There the repositories that call WCF services are injected, app has multiple layers.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:13 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
nawafbarayacommented, Jan 7, 2021

Hi, i had the exact same issue and going to runtime version ~3.0.14916 fixed it, thanks a lot!

0reactions
fabiocavcommented, Mar 17, 2021

@ivan-sam that’s a great update. I’ll close this as resolved, but please let us know if you run into issues.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to define WCF End Point in Azure function?
I have been working with this solution where A client application is supposed to access WCF service via Relay. I have followed this...
Read more >
object initialization can be simplified throws exception
I get the following exception when trying to apply the 'Object initialization can be simplified' code fix: System.InvalidCastException ...
Read more >
Azure Functions error handling and retry guidance
Learn how to handle errors and retry events in Azure Functions, with links to specific binding errors, including information on retry ...
Read more >
[Mono-bugs] Your Bugzilla bug list needs attention.
Open type initializer exception -> http://bugzilla.novell.com/show_bug.cgi?id=322429 Runtime alters sink stack when creating channel ...
Read more >
https://raw.githubusercontent.com/dotnet/samples/m...
Diagnostics Create the Microsoft.Diagnostics.EventSource.Redist Nuget Package The package will be completed once the following is done: - [X] Create project ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found