Scrutor the built-in Dependency Injection (DI)

 

Scrutor is a lightweight .NET library that extends the built-in Dependency Injection (DI) system in ASP.NET Core (or any .NET application that uses Microsoft.Extensions.DependencyInjection) by providing assembly scanning and automatic registration of services.

Key Features of Scrutor

  1. Assembly Scanning
    Automatically registers services by scanning assemblies instead of manually specifying each one. This is helpful in large applications or when following clean architecture or DDD patterns.
  2. Service Registration by Convention
    You can register services based on naming conventions or interface implementation. For example, register all classes that implement a specific interface.
  3. Decorators
    Scrutor supports applying the decorator pattern easily through DI, allowing you to wrap services (e.g., for logging, validation, etc.) without modifying the core implementation.

 

Example Usage

1. Basic Scanning and Registration

csharp

CopyEdit

services.Scan(scan => scan

    .FromAssemblyOf<ISomeService>() // or FromCallingAssembly()

    .AddClasses(classes => classes.AssignableTo<ISomeService>())

    .AsImplementedInterfaces()

    .WithScopedLifetime());

This code:

  • Scans the assembly containing ISomeService
  • Finds all classes that implement ISomeService
  • Registers them with their implemented interfaces
  • Sets the lifetime to Scoped

 

2. Using Decorators

csharp

CopyEdit

services.AddScoped<IService, Service>();

services.Decorate<IService, ServiceDecorator>();

This means:

  • IService is first implemented by Service
  • Then it's wrapped by ServiceDecorator (which takes an IService in its constructor)

Why Use Scrutor?

  • Cleaner Code: Reduces boilerplate code in Startup.cs or Program.cs
  • Better Organization: Encourages organizing services by convention and interface
  • Advanced Scenarios: Supports decorators, filtering, and more powerful DI patterns

 

Comments

Post a Comment

Popular posts from this blog

πŸ”Œ Extension Methods in C#: Power Up Your Code Without Modifying It

πŸ§… Understanding the Onion Architecture: A Clean Approach to Building Scalable Applications

Understanding Dependency Injection: A Modern Guide for Developers

🌐 CORS in .NET Explained: Solving the Cross-Origin Problem Like a Pro

Ensuring Data Integrity: The Backbone of Reliable Systems

πŸ” JWT (JSON Web Token) Explained: Secure Your APIs the Modern Way

πŸ”— SQL JOINs Explained: Mastering Table Relationships

πŸ—‚️ DROP vs DELETE vs TRUNCATE in SQL: What’s the Difference?

πŸ›‘️ SIEM Logs Explained: How to Build Secure and Auditable .NET Apps