Uutiset

Adafyn kuulumisia

Installing NuGet Packages using C#

<p>We’ve been creating a system where we need to download and use NuGet packages dynamically, runtime. To handle this, we use <a href="https://www.nuget.org/packages/NuGet.Core/" target="_blank">NuGet.Core</a>.</p> <h2>Using NuGet.Core</h2> <p>NuGet.Core contains the basic functionality for installing, removing and updating packages. The main classes when dealing with NuGet.Core are <em>PackageRepositoryFactory </em>and <em>PackageManager</em>. PackageRepositoryFactory creates the “connection” into your NuGet repository and PackageManager is used to install the packages. Here’s an example code which covers the following situation:</p> <ul> <li>We have a console app <li>We use local NuGet repository (file system)</li></ul><pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"> var repo = PackageRepositoryFactory.Default.CreateRepository("file://C:/temp/packages");
var packageManager = new PackageManager(repo, _installLocation);

var package = repo.FindPackage("mypackage", SemanticVersion.Parse("1.0.0.0"));

packageManager.PackageInstalled += (sender, eventArgs) =&gt;
{
var fileRoot = System.IO.Path.GetDirectoryName(Path.Combine(eventArgs.InstallPath, eventArgs.Package.AssemblyReferences.First().Path));
Console.WriteLine(fileRoot);
};

packageManager.InstallPackage(package, false, true, true);
</pre>
<p>PackageManager’s even <em><u>PackageInstalled</u></em> usually causes some grief because it is raised only when package is actually installed: If it’s already installed, PackageInstalled-event is skipped.</p>
<h2>Using classes from NuGet runtime</h2>
<p>We use MEF to actually execute the code inside the NuGet packages:</p>
<ol>
<li>Make sure that the packages contains classes which implement known interfaces.
<li>Use DirectoryCatalog to initialize the MEF container.
<li>Use GetExportedValues to get the implementing classes.</li></ol>
<p>For example:</p><pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">packageManager.PackageInstalled += (sender, eventArgs) =&gt;
{
var fileRoot = System.IO.Path.GetDirectoryName(Path.Combine(eventArgs.InstallPath, eventArgs.Package.AssemblyReferences.First().Path));

if (fileRoot == null)
return;

var catalog = new AggregateCatalog(
new DirectoryCatalog(fileRoot, "*.dll"));

var container = new CompositionContainer(catalog);

var activities = container.GetExportedValues&lt;IActivity&gt;();
foreach (var activity in activities)
{
activity.Run();
}
};
</pre>