Skip to main content

Lesson 5 of 8

Service Registration Patterns & Extensions

As your application grows, Program.cs becomes cluttered with hundreds of service registrations. Extension methods on IServiceCollection organize registrations by feature and enable modular architecture - each module owns its own DI setup.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Extension Methods for Clean DI Registration

Extension Methods for Clean DI Registration
// ━━ Feature-based DI extension methods ━━
// Each layer/feature registers its own dependencies

// Infrastructure/DependencyInjection.cs
public static class InfrastructureServiceExtensions
{
    public static IServiceCollection AddInfrastructure(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        // Database
        services.AddDbContext<AppDbContext>(options =>
            options.UseSqlServer(
                configuration.GetConnectionString("DefaultConnection"),
                sql => sql.EnableRetryOnFailure(maxRetryCount: 3,
                           maxRetryDelay: TimeSpan.FromSeconds(5),
                           errorNumbersToAdd: null)));

        // Repositories
        services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
        services.AddScoped<IProductRepository, ProductRepository>();
        services.AddScoped<IOrderRepository, OrderRepository>();

        // External services
        services.AddHttpClient<IPaymentGateway, StripePaymentGateway>(client =>
        {
            client.BaseAddress = new Uri("https://api.stripe.com/");
            client.Timeout = TimeSpan.FromSeconds(30);
        });

        // Redis distributed cache
        services.AddStackExchangeRedisCache(options =>
            options.Configuration = configuration.GetConnectionString("Redis"));

        return services;
    }
}

// Application/DependencyInjection.cs
public static class ApplicationServiceExtensions
{
    public static IServiceCollection AddApplication(this IServiceCollection services)
    {
        // MediatR for CQRS (Module 11)
        services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(ApplicationServiceExtensions).Assembly));

        // AutoMapper
        services.AddAutoMapper(typeof(ApplicationServiceExtensions).Assembly);

        // FluentValidation
        services.AddValidatorsFromAssembly(typeof(ApplicationServiceExtensions).Assembly);

        return services;
    }
}

// Clean Program.cs - one line per layer
var builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddApplication()
    .AddInfrastructure(builder.Configuration)
    .AddPresentation(builder.Configuration); // controllers, swagger, auth

// Placeholder types
class AppDbContext : Microsoft.EntityFrameworkCore.DbContext { }
interface IRepository<T> { }
class EfRepository<T> : IRepository<T> { }
interface IProductRepository { }
class ProductRepository : IProductRepository { }
interface IOrderRepository { }
class OrderRepository : IOrderRepository { }
interface IPaymentGateway { }
class StripePaymentGateway : IPaymentGateway { public StripePaymentGateway(HttpClient c) { } }

Tip

Tip

Practice Service Registration Patterns Extensions in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Service Registration Patterns Extensions from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Service Registration Patterns Extensions is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done