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
- 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. - 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. - 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
Very useful
ReplyDelete