← Back to Tutorials Chapter 6

Modularity

Projects and Solutions

.NET organizes code into projects (single .csproj file) and solutions (.sln file) that group multiple projects together. Solutions are ideal for multi-project applications like a web API plus a class library plus a test project.

dotnet new sln -n MyApp
dotnet new webapi -n MyApp.Api
dotnet new classlib -n MyApp.Core
dotnet new xunit -n MyApp.Tests
dotnet sln add MyApp.Api MyApp.Core MyApp.Tests

Solution Structure

Once added, the solution file tracks each project's path and configuration. Building the solution builds all projects in dependency order:

dotnet build MyApp.sln
dotnet test MyApp.sln

NuGet Packages

NuGet is the package manager for .NET. Packages contain compiled libraries, tools, and metadata. The NuGet gallery at nuget.org hosts hundreds of thousands of packages.

Adding a NuGet Package

dotnet add package Newtonsoft.Json
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 8.0.0

Creating and Publishing a NuGet Package

dotnet pack -c Release
dotnet nuget push bin/Release/MyPackage.1.0.0.nupkg --api-key YOUR_KEY --source https://api.nuget.org/v3/index.json

Dependency Injection

The Microsoft.Extensions.DependencyInjection library provides a first-class DI container. It is the foundation of ASP.NET Core and can be used in any .NET application.

Service Lifetimes

// Transient — new instance every time
services.AddTransient<IMyService, MyService>();

// Scoped — same instance per request/scope (common in web apps)
services.AddScoped<IMyService, MyService>();

// Singleton — single instance for the application lifetime
services.AddSingleton<IMyService, MyService>();

Consuming Dependencies

public class HomeController
{
    private readonly IMyService _service;

    public HomeController(IMyService service)
    {
        _service = service;
    }
}

Configuration System

The Microsoft.Extensions.Configuration package provides a hierarchical key-value configuration system supporting JSON files, environment variables, command-line args, and more.

// appsettings.json
{
    "Logging": { "LogLevel": { "Default": "Information" } },
    "ConnectionStrings": {
        "Default": "Server=.;Database=MyDb;Trusted_Connection=True"
    }
}

// Reading configuration
var connectionString = configuration.GetConnectionString("Default");
var logLevel = configuration["Logging:LogLevel:Default"];
.NET Core modularity
Exercise: Create a solution with a class library and a console app. Add a NuGet reference from the console app to the class library. Register services using DI and read a connection string from appsettings.json.