microsoft / sqlmanagementobjects

Sql Management Objects, an API for scripting and managing SQL Server and Azure SQL Database
Other
127 stars 20 forks source link

Could not load file or assembly Microsoft.Identity.Client, Version=4.22.0.0 #110

Open shandysawyer opened 2 years ago

shandysawyer commented 2 years ago

I have a .NET 4.8 framework Windows application that is using Microsoft.SqlServer.SqlManagementObjects (v161.47027.0) in its own class. I am unit testing that class in a separate .NET 4.8 library test project.

However when I run a test like so:


[Test]
public void SqlAgentJobDoesntExist_ThrowsException()
{
     var connection = new SqlConnectionStringBuilder(ConnectionString); //ConnectionString coming from app.config in the test project
     var sqlAgent = new SqlAgentService(connection);
     Assert.Throws<NullReferenceException>(() => { var result = sqlAgent.ExecuteJob("NotFound"); });
}

It is throwing an error around this bit of code in my service class:

public CompletionResult ExecuteJob(string jobName)
{
    try
    {
        var connection = new ServerConnection(_connectionBuilder.DataSource, _connectionBuilder.UserID, _connectionBuilder.Password);
        var server = new Server(connection);
        var job = server.JobServer.Jobs[jobName]; //<-- throwing error here
...

Error:

Microsoft.SqlServer.Management.Common.ConnectionFailureException : Failed to connect to server XXXXXXXXXXX.
----> System.TypeInitializationException : The type initializer for 'Microsoft.Data.SqlClient.SqlAuthenticationProviderManager' threw an exception.
----> System.IO.FileLoadException : Could not load file or assembly 'Microsoft.Identity.Client, Version=4.22.0.0, Culture=neutral, PublicKeyToken=0a613f4dd989e8ae' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Two reasons this is odd:

  1. The application itself is working fine (the main project), this error is only happening in my unit test project
  2. It's odd because SMO already installs Microsoft.Identity.Client as a dependency when adding as a NuGet package. Why is it asking for this older 4.22 version?
shueybubbles commented 2 years ago

Microsoft.Data.SqlClient has a dependency on 4.22 while the SMO nuget package defines a dependency on 4.35. To resolve the mismatch you need to configure a binding redirect of some sort, whether through an app.config for your test DLL or by writing an assembly resolver in your test code.

The SMO tests have assembly resolvers in code for Newtonsoft conflicts like https://github.com/microsoft/sqlmanagementobjects/blob/98093604e9ede97aa2a9b066279f0bd9d9557c4f/src/UnitTest/Notebook/SmoNotebookTests.cs#L30

That code could really load any assembly just by picking up whatever DLL with that name is in the same folder with the test.