user626528
user626528

Reputation: 14419

How do I properly choose assemblies from referenced NuGet packages?

I'm using the NuGet.Core library to install a package programmatically; this also automatically installs all the dependencies of the package, but some of these packages are multi-target and contain multiple versions of assemblies for different .NET versions.
How do I pick the correct versions of assemblies from these multi-target packages (i.e. in the same way as it's done when installing NuGet packages manually from within Visual Studio)?

Upvotes: 0

Views: 275

Answers (1)

Matt Ward
Matt Ward

Reputation: 47947

You can use the VersionUtility class to find compatible items. This is what NuGet does when installing a NuGet package into a project. You pass the list of all items, such as references in the NuGet package, and the target framework name, such as ".NETFramework, Version=4.0", and the VersionUtility class will return the compatible items.

Some example code taken from NuGet.Core and modified slightly:

List<IPackageAssemblyReference> assemblyReferences =
    GetCompatibleItems(package.AssemblyReferences).ToList();

static IEnumerable<T> GetCompatibleItems<T>(FrameworkName targetFramework, IEnumerable<T> items) where T : IFrameworkTargetable
{
        IEnumerable<T> compatibleItems;
        if (VersionUtility.TryGetCompatibleItems(targetFramework, items, out compatibleItems))
        {
                return compatibleItems;
        }
        return Enumerable.Empty<T>();
}

Upvotes: 1

Related Questions