Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't call/load .NET Core assembly but .NET Standard works fine using Add-Type in PowerShell

Tags:

c#

powershell

While attempting to create a .NET Core class library for PowerShell I'm seeing some strange differences between .NET Standard and .NET Core.

Following this guidance, I've created a simple .NET Standard 2.0 class library and have been able to successfully load it in PowerShell 5.1 and PowerShell 6.0.1 using Add-Type -Path [path].

namespace Animal
{
    public class Dog
    {
        public string Bark()
        {
            return "Woof!";
        }
    }
}

I can call the .Bark() method and see an output in PowerShell 5.1 and PowerShell Core 6.0.1.

When I use the .NET Core 2.2 template to build the same class I can't use it in either PowerShell instance. Code is almost identical:

namespace AnimalCore
{
    public class Dog
    {
        public string Bark()
        {
            return "Woof!";
        }
    }
}

PowerShell 5.1:

Add-Type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

PowerShell Core 6.0.1

Unable to find type [AnimalCore.Dog]

I could happily go on using the .NET Standard template to build my assembly but I'm wondering what the difference is here and how it would be possible to compile this class library for use on .NET Core?

like image 773
Jason Shave Avatar asked Feb 22 '19 21:02

Jason Shave


1 Answers

In reverse order:

how it would be possible to compile this class library for use on .NET Core?

In order for your library to be used by PowerShell Core, you'll have to target .NET Core version 2.1 for now - 2.2 is not yet supported (although it's my understanding that the next release, PowerShell Core 6.2, will see the project migrated to .NET Core 2.2).


I could happily go on using the .NET Standard template to build my assembly but I'm wondering what the difference is here

As you may know, there's not complete feature parity between the .NET Framework and .NET Core - some base class libraries that ship with Windows naturally aren't available in .NET Core, and some of the cross-platform support required in .NET Core results in some APIs behaving differently than in .NET Framework.

The solution to this portability gap is called .NET Standard - it defines the large subset of APIs that perfectly overlap between Framework and Core!

So when you target netstandard2.0 rather than netcoreapp2.2 or netcoreapp2.1, it's a way to ensure that both .NET Framework and .NET Core runtimes can reference and use your library - which is exactly why you find that your code works perfectly in both PowerShell 5.1 and 6.0.1 as long as you target .NET Standard

like image 84
Mathias R. Jessen Avatar answered Nov 12 '22 02:11

Mathias R. Jessen