serilog-aspnetcore icon indicating copy to clipboard operation
serilog-aspnetcore copied to clipboard

Could not load file or assembly Microsoft.Extensions.DependencyModel

Open kvanover opened this issue 3 years ago • 18 comments

Description Unable to start web host when running in .net 5 in a docker container.

Detailed error:

[06:48:15 INF] Starting web host [06:48:15 FTL] Host terminated unexpectedly System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Extensions.DependencyModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.

File name: 'Microsoft.Extensions.DependencyModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' at Area51.Core.Hosting.Diagnostics.Logging.Serilog.HostBuilderExtensions.<>c.<UseDefaultSerilog>b__0_0(HostBuilderContext context, IServiceProvider services, LoggerConfiguration configuration) at Serilog.SerilogHostBuilderExtensions.<>c__DisplayClass3_2.<UseSerilog>b__4(LoggerConfiguration cfg) at Serilog.Extensions.Hosting.ReloadableLogger.Reload(Func2 configure) at Serilog.SerilogHostBuilderExtensions.<>c__DisplayClass3_1.<UseSerilog>b__1(IServiceProvider services) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)

Reproduction New web application, reference serilog-aspnetcore, add 'ReadFrom.Configuration()', build docker file, run. Starting as the console on a development machine does not give this problem. It only occurs when running the docker container.

Additional context I have also referenced -> 'Microsoft.Extensions.DependencyModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. manual as a nuget package but this also didn't help to solve the problem. if you reference only 'Serilog.Settings.Configuration', it also works.

kvanover avatar Apr 27 '21 07:04 kvanover

I am seeing the same issue when trying to use the following code in asp.net .net 5.0: using Common.Logging; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Serilog; using System; using System.IO; using System.Net; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Azure.Identity; using Azure.Core;

// One thing leads to another https://youtu.be/N3xejGTpqJg // https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/april/data-points-ef-core-in-a-docker-containerized-app

IConfiguration configuration = GetConfiguration();

Line 26-->> Log.Logger = CreateSerilogLogger(configuration);

try { Log.Information("Configuring web host Extensions ({ApplicationContext})...", ASPCOREAPIEx.Program.AppName); LogTraceMessage(); LogDebugMessage(); LogInfoMessage(); LogWarningMessage(); LogErrorMessage(); LogFatalErrorMessage(); // Create the IHOST instance and run it CreateHostBuilder(args).Build().Run();

return 0;

} catch ( Exception ex) { Log.Fatal(ex, "Program.cs: ASPCOREAPIEx: Program terminated unexpectedly ({ApplicationContext})!", ASPCOREAPIEx.Program.AppName); return 1; } Serilog.ILogger CreateSerilogLogger(IConfiguration configuration) { var seqServerUrl = configuration["Serilog:SeqServerUrl"]; var logstashUrl = configuration["Serilog:LogstashgUrl"]; return new LoggerConfiguration() .MinimumLevel.Verbose() .Enrich.WithProperty("ApplicationContext", ASPCOREAPIEx.Program.AppName) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.Seq(string.IsNullOrWhiteSpace(seqServerUrl) ? "http://seq" : seqServerUrl) .WriteTo.Http(string.IsNullOrWhiteSpace(logstashUrl) ? "http://logstash:8080" : logstashUrl) .ReadFrom.Configuration(configuration) .CreateLogger(); }

IConfiguration GetConfiguration() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); // builder. // ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(This).Assembly).WithReferences())

// Put the .NET version of the code like oreans does https://github.com/dotnet/orleans/issues/7172
// builder.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(TypeInYourAsm).Assembly).WithReferences())


var config = builder.Build();

if (config.GetValue<bool>("UseVault", false))
{
    TokenCredential credential = new ClientSecretCredential(
        config["Vault:TenantId"],
        config["Vault:ClientId"],
        config["Vault:ClientSecret"]);
    builder.AddAzureKeyVault(new Uri($"https://{config["Vault:Name"]}.vault.azure.net/"), credential);
}

return builder.Build();

} static void LogTraceMessage() { Log.Verbose("This is a trace/verbose..."); } static void LogDebugMessage() { Log.Debug("This is a debug message..."); }

Runs fine under .net50 target on Visual Studio, but fails when running under Linux Docker build using the following DockerFile:

FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base WORKDIR /app EXPOSE 80 EXPOSE 443

#FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build WORKDIR /src COPY ["ASPCOREAPIEx.csproj", "."] RUN dotnet restore "ASPCOREAPIEx.csproj" COPY . . WORKDIR "/src/" RUN dotnet build "ASPCOREAPIEx.csproj" -c Release -o /app/build

FROM build AS publish RUN dotnet publish "ASPCOREAPIEx.csproj" -c Release -o /app/publish

FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "ASPCOREAPIEx.dll"]

docker build . docker run xyz

Unhandled exception. System.IO.FileLoadException: Could not load file or assembly 'Microsoft.Extensions.DependencyModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)

File name: 'Microsoft.Extensions.DependencyModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'

at <Program>$.<<Main>$>g__CreateSerilogLogger|0_0(IConfiguration configuration)

at <Program>$.<Main>$(String[] args) in /src/Program.cs:line 26

john-kruebbe-dxc avatar Sep 16 '21 20:09 john-kruebbe-dxc

Hi! I'm pretty sure this will be a deployment/publishing quirk and not a direct consequence of anything we're doing in this library (this package is used with .NET 5 on Docker a lot).

If you track it down to a problem with one of the Serilog libs though, please do give us a heads-up!

Cheers, Nick

nblumhardt avatar Sep 17 '21 00:09 nblumhardt

Having the same issue here

rodrigoramirez93 avatar Jan 03 '22 18:01 rodrigoramirez93

@rodrigoramirez93 Hi, can you provide minimal example that reproduces the problem? Thanks!

skomis-mm avatar Jan 03 '22 18:01 skomis-mm

@skomis-mm

I was trying to dockerize a net6 web API that contained the package coverlet.collector 3.1, which seems to be requesting the dependency Microsoft.Extensions.DependencyModel/2.1.0 that somehow collide with serilog's Microsoft.Extensions.DependencyModel/5.0.0 dependency.

For future developers hitting this issue:

  1. Publish your app into a folder: dotnet publish -o ./publish
  2. Search for Microsoft.Extensions.DependencyModel in all *.json files
  3. Look for other third parties that might request the Microsoft.Extensions.DependencyModel.

In my case, as I'm building the docker image for local development only, just unchecking tests assemblies from solution properties/configuration properties... will do the trick. Don't know how would I fix this otherwise

rodrigoramirez93 avatar Jan 03 '22 20:01 rodrigoramirez93

it happens to me intermittently. I also use Serilog.Settings.Configuration. then I also already explicitly included Microsoft.Extensions.DependencyModel

I'm deploying to AWS Lambda (containerized -- Docker).

I think it happens because I also have unit tests that use coverlet.collector which seems to reference the same Microsoft.Extensions.Dependency.

so the solution is to ONLY include the .csproj I want to publish in my dockerfile instead of publishing the .sln file.

this issue sucks because you can only see the problem AFTER deploying because it only happens during runtime.

aiampogi avatar Jan 14 '22 05:01 aiampogi

Hi @aiampogi , @rodrigoramirez93 looks like a problem with dotnet publish on sln which can have unpredicted side effects.

skomis-mm avatar Jan 14 '22 11:01 skomis-mm

Hi ! The same problem with azure functions v4 net6 Tried every available suggestion from web, nothing works Repo to reproduce https://github.com/baio/func-test

baio avatar Feb 22 '22 20:02 baio

Hey Baio, try to not publish the tes dll, search for the tag isPublishable false for the csproj

rodrigoramirez93 avatar Feb 22 '22 21:02 rodrigoramirez93

image

<PropertyGroup>
	...	<IsPublishable>False</IsPublishable>
	</PropertyGroup>

Added, doesn't help

baio avatar Feb 23 '22 06:02 baio

I have another repro with .Azure Functions v4 net 6/ Serilog.AspNetCore 5.0.0 The Function runs just fine with Serilog.AspNetCore 4.2.0, which has a dependency to Serilog.Settings.Configuration 3.3.0 and then Microsoft.Extensions.DependencyModel 2.1.0 After upgrading to Serilog.AspNetCore 5.0.0 I get the runtime exception Could not load file or assembly 'Microsoft.Extensions.DependencyModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.

No docker involved. Looks like some dependency inconsistencies.

ranasch avatar Feb 28 '22 17:02 ranasch

I have the same exact issue @ranasch mentioned.. I Tried also to update Microsoft.Extensions.DependencyModel to 6.0.0 but still no hope.

hunyhabib avatar Mar 03 '22 08:03 hunyhabib

Hi @ranasch @hunyhabib try this workaround

skomis-mm avatar Mar 03 '22 09:03 skomis-mm

As mentioned by @skomis-mm after adding the below in .csproj issue got resolved.
<FunctionsPreservedDependencies Include="Microsoft.Extensions.DependencyModel.dll" />

shani11 avatar Mar 11 '22 03:03 shani11

In my case, I didn't have functions app, so FunctionsPreservedDependencies didn't work.

What worked instead, was manually adding these packages to csproj.

<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyModel" Version="6.0.0" />

Hope it helps

DawidNowak avatar Mar 25 '22 10:03 DawidNowak

@shani11 @DawidNowak

The combination of both <FunctionsPreservedDependencies Include="Microsoft.Extensions.DependencyModel.dll" /> and <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyModel" Version="6.0.0" />

Was the fix for me in order to get functions v4 with net6.0 runtime working.

Thank you both for the solutions!

rob-thijssen avatar Apr 15 '22 13:04 rob-thijssen

I also faced this issue after migration Azure function to v4(.Net6). Could not load file or assembly 'Microsoft.Extensions.DependencyModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified. Have Serilog.Settings.Configuration 3.3.0 which has refference to Microsoft.Extensions.DependencyModel v3.0.0

petro-konopelko avatar May 04 '22 16:05 petro-konopelko

Guys, the way I fixed this was to use the version of the .NET libraries that they did when I compiled my code. Alternatively, you could get them to compile with the version you are using. The mismatched version is the cause of this issue after many many hours of struggles with it. I hope that this helps as it is purely a nugit version dependency issue. One other thing is that I hacked their incorrect version string into the library with the mismatch problem. Sorry I don't know which one any more. Your printout would tell you the library its trying to load. Check to see that what they are expecting is what Nuget library has. I suggest that Serlog folks to check their version strings and update to the latest LTS .NET version. We really like what you guys have done with Serilog, but if we cant compile with latest .NET versions, then it is kind of hard to use your libraries.

john-kruebbe-dxc avatar May 04 '22 18:05 john-kruebbe-dxc

I think Serilog.Settings.Configuration should be updated and adjusted to .net 5+ Currently is is not adjusted: <TargetFrameworks> netstandard2.0;net451;net461 </TargetFrameworks>

It is my first guess. Do you need help with it? I see bug was created long time ago. I also had this issue.

Krysztal avatar Jan 17 '23 18:01 Krysztal

I had to change the version of the .net library that was being pointed to to fix the issue and it seems to occur on every new version of .net.

With Kindest Regards,

John Kruebbe Lead Solutions Architect Text Only if not on Teams: 650-284-9575

From: Krysztal @.> Sent: Tuesday, January 17, 2023 12:32 PM To: serilog/serilog-aspnetcore @.> Cc: KRUEBBE, JOHN @.>; Comment @.> Subject: Re: [serilog/serilog-aspnetcore] Could not load file or assembly Microsoft.Extensions.DependencyModel (#245)

I think Serilog.Settings.Configuration should be updated and adjusted to .net 5+ Currently is is not adjusted: netstandard2.0;net451;net461

It is my first guess. Do you need help with it? I see bug was created long time ago. I also had this issue.

— Reply to this email directly, view it on GitHubhttps://clicktime.symantec.com/15tSyRUS3seRN3MArsKr4?h=xe7I9HAWwTIzL_fCfU8hry09rU1gugSr_4FxRzfcA5c=&u=https://github.com/serilog/serilog-aspnetcore/issues/245%23issuecomment-1385856230, or unsubscribehttps://clicktime.symantec.com/15tStbH9bFxpx6XFKJvhS?h=7ld1cvWrIPECdoD3oszrMfuFTC0th6Hbr4U5oQsOv88=&u=https://github.com/notifications/unsubscribe-auth/AVVJIN4BEHHIPHC6WGGJOJLWS3QR7ANCNFSM43UN64MQ. You are receiving this because you commented.Message ID: @.@.>>

john-kruebbe-dxc avatar Jan 18 '23 15:01 john-kruebbe-dxc

I am seeing the same issue. Could you please help?

anandthirumala avatar Jan 19 '23 22:01 anandthirumala

I am seeing the same issue. Could you please help?

Use DependencyInjection, DependencyModel libraries explicitly in your project where do you use Srilog.Aspnetcore. Also do not use sln to build project in pipeline. Instead build main csproj project separately.

Krysztal avatar Jan 20 '23 05:01 Krysztal

I am facing the same issue in .NET 7. I've tried all the solutions I found online, but none of them work. Is there any update available? I really don't want to choose between Docker and Serilog.

mcai25658 avatar Jun 14 '23 10:06 mcai25658

Hi all! 👋

It appears that this error message results from multiple different underlying conditions - there are at least three different solutions reported in the thread but it's not clear that they are all addressing the same problem.

In addition, Serilog.Settings.Configuration v7 now targets all of the v7 versions of the various Microsoft.* dependencies, so the fundamentals have changed considerably since the first post in this thread.

These factors combine to make it difficult to provide help in this thread, so I'm going to close it now.

If you're hitting the Could not load... issue, and you've tried the workarounds in this thread, as well as updating to the latest versions of all of your dependencies, then I'd suggest:

  1. Post absolutely all the detail you can into a new post on Stack Overflow, where it's likely you'll find someone with the answer covering your specific situation; the serilog tag is the way to go for this; or
  2. If you've narrowed it down to a bug in this package, or have figured out something we could do better to improve compatibility with your environment, please open a fresh issue, again providing absolutely all possible details on your usage scenario.

Thanks and good luck with it!

nblumhardt avatar Jun 14 '23 23:06 nblumhardt