Solvedazure functions host Azure function project doesn't copy system.private.servicemodel.dll to the output directory

From @Lxiamail on October 2, 2018 0:35

When Azure function references and uses one of WCF core packages (like system.servicemodel.http), system.private.servicemodel.dll, which system.servicemodel.http depends on, is not copied to output directory together with system.servicemodel.http. The azure function fails for can't find system.private.servicemodel.dll. Looks like other WCF core dependencies (like system.servicemodel.primitives.dll) are copied correctly, but system.private.servicemodel.dll. My guess is that Azure function may not handle the reference assembly, façade and implementation assembly pattern correctly.
Some background of WCF Core packages, system.servicemodel.*.dll (like system.servicemodel.http) are reference assemblies (in ref directory of the package) facade assemblies (in lib directory of the package), The façade assemblies don't have implementation, all they do is typeforward to the implementation assembly system.private.servicemodel.dll. App never directly references to system.private.servicemodel.dll. .NET Corefx follows the same façade and implementation pattern. The difference between WCF Core packages and .NET CoreFX packages is .NET CoreFX are in .NET Core SDK as shared framework, but WCF Core doesn't. This is why mscorlib.dll is not copied to app output directory, but still can be loaded.

OS: windows 10 version 1803 (OS build 17134.286)

VS: VS pro 2017 version 15.7.5

Repro steps:

Create a new Azure function http trigger Project,
Add system.servicemodel.http Nuget package to the reference using NugetPackage manager
Use this repo to file issues in documentation or the Functions Visual Studio tooling.
Adding the follow code in Function1.Run() function to make the function to use something implemented in WCF Core packages.
System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
binding.Name = "binding1";

Build and debug the azure function in VS, after the function is trigger by Http request, you will get the following error:
[10/1/2018 11:39:36 PM] Executing 'Function1' (Reason='This function was programmatically called via the host APIs.', Id=67985bea-8a52-431a-8d65-4ded513269ce)
[10/1/2018 11:39:36 PM] Exception during runtime resolution of assembly 'System.Private.ServiceModel, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a': 'System.InvalidCastException: [A]System.AppDomain cannot be cast to [B]System.AppDomain. Type A originates from 'System.Private.CoreLib, Version=, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' in the context 'Default' at location 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.9\System.Private.CoreLib.dll'. Type B originates from 'System.Runtime.Extensions, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' in the context 'Default' at location 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.9\System.Runtime.Extensions.dll'.
[10/1/2018 11:39:36 PM] at Microsoft.Azure.WebJobs.Script.Description.FunctionAssemblyLoader.ResolveAssembly(Object sender, ResolveEventArgs args) in C:\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\FunctionAssemblyLoader.cs:line 66'
[10/1/2018 11:39:36 PM] Unable to find assembly 'System.Private.ServiceModel, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Are you missing a private assembly file?
[10/1/2018 11:39:37 PM] Executed 'Function1' (Failed, Id=67985bea-8a52-431a-8d65-4ded513269ce)
[10/1/2018 11:39:37 PM] System.Private.CoreLib: Exception while executing function: Function1. FunctionApp4: Could not load file or assembly 'System.Private.ServiceModel, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

Copied from original issue: Azure/Azure-Functions#974

44 Answers

✔️Accepted Answer

I had to create a CopyToPublishDirectory ItemGroup and specify direct path to the assembly, just like in the Build target. This way it's picked up correctly when publishing, and I have the publish working from both local and from DevOps pipeline.

Edit: CopyToOutputDirectory ItemGroup doesn't do anything in this case and I don't even have that in my .csproj

  this is temporary workaround for issue 
  also requires nuget package
  <Target Name="CopySPSM" BeforeTargets="Build">
    <Copy SourceFiles="$(USERPROFILE)\.nuget\packages\system.private.servicemodel\4.5.3\runtimes\win\lib\netstandard2.0\System.Private.ServiceModel.dll" DestinationFolder="$(OutputPath)\bin" />
    <None Include="$(USERPROFILE)\.nuget\packages\system.private.servicemodel\4.5.3\runtimes\win\lib\netstandard2.0\System.Private.ServiceModel.dll" CopyToPublishDirectory="Always" />
  <!--end workaround-->

Other Answers:

Still won't work for me, even with the workarounds. I simply cannot compile a function project that contains a service reference. I always get:

C:\Users\nils.nuget\packages\\1.0.27\build\netstandard1.0\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error : System.IO.FileNotFoundException: Could not load file or assembly 'System.Private.ServiceModel, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Das System kann die angegebene Datei nicht finden.
1>C:\Users\nils.nuget\packages\\1.0.27\build\netstandard1.0\Microsoft.NET.Sdk.Functions.Build.targets(41,5): error : File name: 'System.Private.ServiceModel, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

Error generating functions metadata

@fabiocav, this arguably shouldn't have been closed. Or at least, I wouldn't consider this closed until such a time when "workarounds" aren't needed anymore. Would you agree?

I had to alter my custom MSBuild <Target>s slightly from what was provided above. The function.deps.json wasn't getting included in my ZIP package; not sure if the prior solution works if you don't use ZIP package deployments, I didn't bother checking. Here's what I went with:

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
  <!-- -->
  <Exec Command="copy $(OutDir)$(ProjectName).deps.json $(OutDir)bin\function.deps.json" />
<Target Name="PostPublish" BeforeTargets="CreateZipFile">
  <!-- -->
  <Exec Command="copy $(PublishDir)$(ProjectName).deps.json $(PublishDir)bin\function.deps.json" />

Only meaningful change from above was revising PostPublish to use BeforeTargets="CreateZipFile".

Related Issues:

azure functions host using appsettings.json + IConfiguration in Function App
I have the same issue as well In the context of a Function an ExecutionContext object is injected fr...
azure functions host Common errors when upgrading to 2.0.12050 (or newer)
I'm seeing the same dependency errors as @davemurphysf along with a few other dependency errors with...
azure functions host Azure function project doesn't copy system.private.servicemodel.dll to the output directory
I had to create a CopyToPublishDirectory ItemGroup and specify direct path to the assembly just like...
azure functions host Support .NET Standard 2.0 class libraries
I think this is still not fixed I have an Azure Functions project referencing a .NET Standard 2.0 pr...
azure functions host ILogger is not injected when using new DI functionality
Just to correct myself it doesn't throw an exception in my case but it doesn't log anything Tested i...
azure functions host Allow External Startup to update the config when Runtime Scale Monitoring is enabled
Hi Guys any update on this Now we can include appsettings by doing and we should be able to use thos...
serverless How do I enable CORS?
@lakinducker Thanks No problem! I updated your comment with the corresponding markdown and now the i...
serverless Error: spawn java ENOENT
Have you tried running sls dynamodb install? This downloads the DynamoDb libs you need. ...
serverless Schedule event not created when supplying options
Sorry this was user error and I actually just had the wrong indentation Correct indentation ...
serverless Serverless using AWS profiles only half working
You can use AWS Profiles with Severless including IAM cross-account role assumption ...
serverless Narrowing the Serverless IAM Deployment Policy
I think I have the serverless deployment policy nailed at this point A bit more testing is in order ...
serverless Ignore check for unchanged files after failed deployment
Have you tried to use sls deploy --force @tom10271 ? After a failed deployment due to remote (CloudF...
serverless Serverless Error - Function not found...
I had the same problem after killing a running sls deploy @mrosett's workaround worked for me as wel...
serverless Cannot deploy/remove stack because S3 bucket is gone
Here is a workaround that's been working for me without needing --force: Run sls deploy to generate ...
serverless Allow explicitly specifying serverless.yml file in CLI options or env var
We should have a command like sls deploy --file serverless-foo.yml This is a (Feature Proposal) Desc...
serverless Unable to deploy to Serverless due to 'empty zip'
Yeah Node version was the problem Here's a quick script that I made if anyone needs it: ...
serverless AWS Now Supports Max Retry Attempts
Although the async config can be added as a custom resource I would argue that limiting the retry at...
serverless FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
Had similar issues with largish typescript projects and serverless-webpack-plugin Try export NODE_OP...
serverless Access Outputs from CF template in serverless.yml
RE: cross-stack references.. Hi y'all Trying to transition to v1 and porting my CF template too I am...
serverless Deploy: pathmapping - Invalid stage identifier specified.
After some digging I figured out that the cause here was basically order of ops on the deploy ...
serverless Unable to remove serverless stack that doesn't use API gateway...
In my case I have not http events but I had declared apiKeys under provider I solved this problem ...
serverless FetchError: network timeout on
I couldn't find a correct way to fix it so I ended up disabling slsstats so it would no longer make ...
serverless graceful-fs crashes with "RangeError: Maximum call stack size exceeded"
Same problem here graceful-fs not being graceful. ❗️ NOTE FROM MAINTAINERS ❗️ This issue is result o...
serverless AWS HTTP API: Support IAM and Lambda authorizers
Hello folks thanks to everyone for your patience on this one Unfortunately due to other ongoing task...
serverless Support all intrinsic functions for SNS definition
Just figured out This is a Bug Report Description The docs state ...
serverless Can't subscribe to events of existing S3 bucket
@flomotlik I feel like we need this support but for a different reason than most of the other commen...
serverless AWS SAM Integration
I don't think SAM needs to be a breaking change AWS recently announced their Serverless Application ...
serverless Allow for escaping of variable syntax in serverless.yml
Maybe escaping should follow the same pattern as terraform; provide a double dollar sign ($${}) opti...
serverless Golang, internal server error? Path Error
Hi guys I had same issue Here is a working code example just add StatusCode: 200 ...
serverless Concat multiple function files
TL;DR: We got it working example shown below Hey fellas I have a base code with some legacy apis ...
serverless Mac: aws-go-mod deploy failed Uploaded file must be a non-empty zip
Thanks everyone for checking out and confirming that it's in fact related to node v15.6.0 ...
serverless AWS API Gateway stages are deployed as different API instances (no AWS stages are used)
In regards to #2918 (since that was marked as a duplicate to this) This is a (Bug Report) Descriptio...
serverless Profile [profilename] does not exist. Using Cross account roles. credentials_source=EcsContainer
@ghinks does it work if you set the aws-sdk's AWS_SDK_LOAD_CONFIG env var option? ...
serverless module initialization error: Error
For me this was down to using the bcrypt module The version in my node_modules directory was compile...
serverless Support custom target path inside ZIP file when packaging
I still think this should be part of the core functionality as this is really common use case on lam...
serverless Windows: Uploaded binaries cannot be executed
Some kind of workaround is really needed because go applications can not be used if deployed using w...
serverless Cross region SNS trigger
This is now supported in cloudformation however you have to add target region within cfn ...
serverless CodeSHA256 is different from current CodeSHA256 in $LATEST
Adding versionFunctions: false to the provider property of serverless.yml is a possible workaround. ...
serverless Serverless + NodeJS v8.0 = error on sls deploy
Looks like this was fixed with v8.1.0 I was able to verify it with that version so this issue can pr...
serverless Deploy fails with error 'An error occurred: ServerlessDeploymentBucketPolicy - The bucket policy already exists on bucket...''
Hello 👋 In recent release v2.16.0 skipPolicySetup setting was introduced which should allow avoidin...
serverless function run causes aws-sdk error 'ConfigError: Missing region in config'
I ran into the same thing I think the root cause is the AWS JavaScript SDK not setting a region by d...
serverless s3 events can't refer to existing bucket
Hey @razbomi thanks for commenting 👍 A quick solution would be to overwrite the HelloLambdaPermissi...
serverless Serverless package does not include all modules when a package.json file is provided
I'm experiencing the same issue in version 1.26.0 Any one else? This is a (Bug Report) Description W...
serverless Permission error when using serverless deploy
I have this error every time I try to deploy I sudo rm -r the downloadCacheslspyc directory and then...
serverless Rate exceeded
Ok Then this is a severe bug in the variable resolution part of Serverless Description I have 8 time...
serverless Go function is not supporting local invoke
Hey folks I've created a PR that adds support for golang & other runtimes by utilizing the lambci/la...
serverless Postinstall script installation fails when installing locally
as a quick fix you can use npm install --legacy-bundling in your project dir This will make sure tha...
react starter kit How to call child component method from parent?
For example you can use Refs to Components approach like so: Demo:
Zappa bad magic number in 'application': b'\x03\xf3\r\n': ImportError
I was able to fix this too by doing find -name \*.pyc -delete Mine definitely wasn't caused by PY2 -...