Repository navigation
Description
In our particular case, we have a custom shell around ConsoleShell that upon start up loads Microsoft.WindowsAzure.Storage.dll into the current app domain. Once the shell is up, we couldn't import for example Az.Accounts module because it depends on a different version of Microsoft.WindowsAzure.Storage.dll. Since this is a more general problem with PowerShell Core, I posted the issue here instead of over at Azure PowerShell. Effectively, I'm looking for a workaround for issue #2083.
Attempt 1:
custom assembly resolve
using Microsoft.PowerShell;
using System;
using System.Diagnostics;
using System.Reflection;
namespace Test
{
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
ConsoleShell.Start("Hello", "", new string[0] { });
}
private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
Debugger.Launch();
return null;
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.0.0-rc.1" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.PowerShell.ConsoleHost">
<HintPath>$(NuGetPackageRoot)\microsoft.powershell.consolehost\7.0.0-rc.1\runtimes\win\lib\netcoreapp3.1\Microsoft.PowerShell.ConsoleHost.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
Problem:
When run two import (Import-Module C:\version1\assembly.dll; Import-Module C:\version2\assembly.dll) with different versions of the assembly, I hit error of Import-Module: Assembly with same name is already loaded but the AssemblyResolve event was not raised.
Attempt 2:
binding redirect through config file
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.WindowsAzure.Storage" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.3.3.0" newVersion="9.3.3.0" />
</dependentAssembly>
</assemblyBinding>
Problem:
Run into the same error above
Attempt 3:
run any external commands with Invoke-Command -Session, this basically out-sourced the command on a different app domain and avoid the version collision.
Problem:
This seems to be the only workaround I can come up with, but it's really inconvenient to jump back and forth PS sessions.
Question:
Any better workaround?
Activity
iSazonov commentedon Jan 14, 2020
/cc Dongbo Wang (@daxian-dbw) for information.
SeeminglyScience commentedon Jan 14, 2020
PowerShellEditorServices had some similar issues, Rob Holt (@rjmholt) recently worked around that with
AssemblyLoadContext's.Here's the load context class.
And here's where he sets it up for use.
rjmholt commentedon Jan 14, 2020
There's only one AppDomain in .NET Core, but as it happens this is much easier to make work in .NET Core than in .NET Framework (i.e. if you have a need to do this in .NET Framework you need inter-AppDomain serialisation and a whole lot of
ManagedByRefObjectwork).Yeah, if you control the assembly load of your dependency, you can load it into a new assembly load context. In PSES we accomplish this as follows:
This assembly resolve setup means you don't need to use reflection anywhere, you just redirect loading through a new ALC at runtime. But it requires some layers:
We've discussed getting this into PowerShell itself for modules, but it's quite complex and not planned currently, so unlikely to happen within the next 12 months at least.
rjmholt commentedon Jan 14, 2020
I should say that if you're rehosting PowerShell, you can condense the layers I describe above; you'll just have:
ritchxu commentedon Jan 14, 2020
Rob Holt (@rjmholt) first and foremost, thanks a ton for your details write-up, it's extremely helpful!
Some clarification:
Follow-up questions:
return nullto let the default ALC to resolve?AssemblyLoadContext?daxian-dbw commentedon Jan 14, 2020
I want to point out that it won't work well to load PowerShell into a custom ALC. PowerShell depends on
Assembly.LoadFromheavily especially in module loading, butAssembly.LoadFromwill load an assembly to the default ALC, so it will result in conflicts.SeeminglyScience commentedon Jan 14, 2020
That's probably a scoping issue. By the time your resolving handler is invoked,
$customContextis no longer a variable. You'd have to do something like[System.Runtime.Loader.AssemblyLoadContext]::Default.add_Resolving($onAssemblyResolve.GetNewClosure())but really you're better off doing it from C#.rjmholt commentedon Jan 14, 2020
Oh sorry! To be clear, hosting PowerShell you should host it in the default ALC, but load the dependency into a custom ALC.
Anyway, it sounds like you really just want a module here.
So you don't really need this, but if you don't then the only way to use the dependency APIs you need is by using reflection, which is slower, more error prone and generally less convenient. But you need some unique way to call the API from one assembly and not the other. The two ways to do this are reflection or implicit runtime redirection through a facade API, since just calling the API the normal way in code running in the default ALC will result in you calling the other dependency API.
PowerShell has its own assembly resolve event that fires before yours. When you load the Az module, that loads its immediate assembly. That assembly then needs its dependencies, which aren't found in $PSHOME (.NET's app root here), so PowerShell's resolve event handler gets called, which looks in the directory where that first assembly is loaded.
So for example:
OurModule\OurModule.psd1OurModule.dllisolatedDeps\FacadeApi.dllSharedDep.dllAzModule\AzModule.psd1AzModule.dllSharedDep.dllWhen you load
OurModule, you loadOurModule.dllwhich creates the custom ALC and adds a resolve event that checks ifFacadeApiis the requested assembly and if so looks inisolatedDepsto loadFacadeApi.dllin the custom ALC and take the result of that and return it in the resolve event handler for the default ALC. The custom ALC just looks for anything its asked for inisolatedDepsand that's how it finds theSharedDep.dllin theisolatedDepsdirectory. WhenOurModuleis loaded, PowerShell fires its resolve handler, looks inOurModule\and finds nothing, so we go to your resolve event, which only looks for theFacadeApi.dll.When you load
AzModule, whether before or after, PowerShell loads the module which directly loadsAzModule.dll. That assembly depends on another particular version ofSharedDep.dll(or could be the same one, doesn't matter). That's not loaded into the default ALC at any time, so always fires the resolve event, which PowerShell handles, looks forSharedDep.dllinAzModule\, finds it, and successfully loads. If some assembly doesn't exist by does in theisolatedDepsdir and you fall back to your resolve event handler, you ensure you don't load that by having the resolve there only look forFacadeApi.dlland letting the custom ALC (which you can only get into through that DLL) handle any other dependencies.So the two never clash. But it depends on the
FacadeApi.dllexisting and being unique to your module. It's the veil between the two contexts.The other way to do it is to load your
SharedDep.dllahead of time in the custom ALC, but then you're forced to use reflection to call into its APIs.ritchxu commentedon Jan 16, 2020
Rob Holt (@rjmholt) I think I'm getting closer with your extremely useful explanation above 🙇
Using the PSES as an example, if I understood correctly from the code, here is what happens:
Microsoft.PowerShell.EditorServicesusing the custom ALCLoadmethod).If I understood correctly, when I applies the same logic in my code, the overwritten
Loadwas not invoked, any clue how that could happen?Alternatively, I played with following approach instead:
This seems to be working, and here is what I assumed happening:
testContextAzmodule, PS will resolve all its dependencies to default ALC and no conflict occurredritchxu commentedon Jan 17, 2020
The problem with the approach above is, (at least what seems to be), if I import
Azmodule first and say it loads a dependencydep.1.dllwhich my module has a different version of, saydep.2.dll. Whendep.2.dllwas later loaded, it seems it's loadingdep.1.dllinstead of going through my custom ALC'sLoadmethod, hence jeopardize the separation. Why wouldn't the custom ALC'sLoadmethod not invoked in this case?rjmholt commentedon Jan 17, 2020
So the important details are:
For example:
Also, I'm not entirely sure why your custom ALC's load isn't being called, but the way I approached it was to log things everywhere to trace the logic
rjmholt commentedon Jan 17, 2020
One thought here: if an assembly is loaded into a context and you try to load another assembly of the same name into that context, it won't try to load the new one and there won't be any resolve event either. So it may be that you've already loaded the assembly you want into the default ALC, meaning no resolve event, meaning no load call on the custom ALC.