Lecture Topics:
No Lab
A shared assembly is a reusable library (typically a .dll
) that can be used by multiple applications, often strong-named and deployed to the Global Assembly Cache (GAC) or distributed via NuGet.
Definition:
.dll
, designed for reuse across applications.Create a Class Library (.NET 6) project in Visual Studio 2022:
// SharedLibrary/EmployeeLibrary.cs
namespace SharedLibrary
{
public class EmployeeLibrary
{
public string GenerateEmployeeId() => $"E{Guid.NewGuid().ToString().Substring(0, 4)}";
public void DisplayEmployee(string name) => Console.WriteLine($"Employee: {name}");
}
}
Build to generate SharedLibrary.dll
.
Using .NET CLI:
dotnet new classlib -o SharedLibrary
dotnet build
Referencing the Assembly:
In Visual Studio: Right-click project → Add → Project Reference → Select SharedLibrary
.
In .csproj
:
<ItemGroup>
<ProjectReference Include="..\\\\SharedLibrary\\\\SharedLibrary.csproj" />
</ItemGroup>
Usage:
// Program.cs in Console App
using SharedLibrary;
var lib = new EmployeeLibrary();
Console.WriteLine(lib.GenerateEmployeeId()); // Outputs: E1234
lib.DisplayEmployee("Alice"); // Outputs: Employee: Alice
Key Points:
Shared assemblies are typically strong-named for GAC deployment (see Session 10).
In .NET 6, NuGet packages are preferred over GAC for sharing libraries.
Create a NuGet package:
dotnet pack
dotnet nuget push SharedLibrary.1.0.0.nupkg --source <https://api.nuget.org/v3/index.json>
Why This Matters:
Custom attributes allow adding metadata to code elements, which can be queried at runtime using reflection.
Derive from System.Attribute
, typically suffixed with Attribute
.
Example:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class AuditAttribute : Attribute
{
public string Description { get; }
public AuditAttribute(string description) => Description = description;
}
[Audit("Employee class for HR system")]
public class Employee
{
public string Name { get; set; }
[Audit("Method to display employee details")]
public void Display() => Console.WriteLine(Name);
}