Location>code7788 >text

Simplifying Core Dependency Injection (DI) Registration - Scrutor

Popularity:152 ℃/2024-12-12 21:12:32

Simplifying Core Dependency Injection (DI) Registration - Scrutor

Scrutor is an open source library designed to simplify the registration process for Dependency Injection (DI) in Core applications. By automatically scanning the types in the program set and automatically register services according to the rules provided .

Basic use

Install using the NuGet Package Manager:

dotnet add package Scrutor

move

  • Selector: Specifies the service implementation to be registered.
  • Registration Strategy: Strategies for handling duplicate services.
  • Services: Specifies the specific implementation of the service.
  • Lifetime: The life cycle of the service, e.g. Singleton, Scoped, Transient.
  1. Selecting a Program Set: Specifies the type of program set to scan from.
(scan => scan
 .FromAssemblyOf<MyClass>(); // scan from the assembly containing MyClass
  1. add a class: Filter the classes that need to be registered.
(scan => scan
 .FromAssemblyOf<MyClass>()
 .AddClasses(classes => (t => ("Service"))); // register only classes ending in Service
  1. Specify the registration method: Specifies which interfaces the class should be registered for.
(scan => scan
 .FromAssemblyOf<MyClass>())
 .AddClasses(classes => (t => ("Service"))))
 .AsImplementedInterfaces(); // Register all interfaces as implemented
  1. Setting the life cycle: Sets the life cycle for a registered service.
(scan => scan
 .FromAssemblyOf<MyClass>()
 .AddClasses(classes => (t => ("Service")))
 .AsImplementedInterfaces()
 .WithScopedLifetime(); // set toScopedlife cycle

Advanced Use

Perform service scanning (Scanning)

  • FromAssemblyOf()From a file that contains the specified type ofT The program's centralized scanning service.
  • FromAssembliesOf(params Type[] types)Multiple types can be specified and Scrutor will scan all assemblies that contain these types.
  • FromCallingAssembly()scanning callScan The set of programs for the method.
  • FromExecutingAssembly()Scanning in progressScan The set of programs for the method.
  • FromEntryAssembly()Scanning the application's entry assembly (usually the assembly containing theMain (the set of programs for the method).
  • Wait...

Perform service decoration (Decoration)

Service decoration is a technique for dynamically adding additional functionality to a service without changing the existing service implementation.

Use Cases

The decorator pattern, which allows you to add behavior to services without modifying existing classes. For example, add behavior to theIMessageSender interface to add a logging decorator:

public interface IMessageSender
{
 void SendMessage(string message);
}

public class EmailMessageSender : IMessageSender
{
 public void SendMessage(string message)
 {
  ($"Sending email: {message}");
 }
}

public class LoggingMessageSender : IMessageSender
{
 private readonly IMessageSender _inner;
 public LoggingMessageSender(IMessageSender inner)
 {
  _inner = inner;
 }
 public void SendMessage(string message)
 {
  ("Starting to send message...");
  _inner.SendMessage(message);
  ("Message sent successfully.");
 }
}

// utilization Scrutor Registering services and decorators
(scan => scan
 .FromAssemblyOf<IMessageSender>()
 .AddClasses(classes => <IMessageSender>())
 .AsImplementedInterfaces()
 .WithTransientLifetime());
<IMessageSender, LoggingMessageSender>();

life cycle management

To set up different lifecycles for specific services, you can chain calls to different lifecycle settings

(scan => scan
    .FromAssemblyOf<CombinedService>())
    .AddClasses(classes => <ICombinedService>()) // Filter for services
    .AsSelfWithInterfaces() // register as an interface
    .WithSingletonLifetime()) // set to Singleton lifecycle

// For other services, set the Scoped lifecycle
.AddClasses(x => (typeof(IOpenGeneric<>))) // You can turn off generic types.
    .AsMatchingInterface()
    .WithScopedLifetime(); // set to Scoped lifecycle

multiple filtration

(scan => scan
    .FromAssemblyOf<MyService>()
    .AddClasses()
    .UsingRegistrationStrategy() // If the service already exists, skip registration
    .AsSelf()
    .WithTransientLifetime());

Chain Registration

Scrutor allows you to integrate multiple scans into one call chain, applying different subsets of rules for different classes:

(scan => scan
 .FromAssemblyOf<Startup>()
 .AddClasses(classes => (t => ("Repository")))
  .AsImplementedInterfaces()
  .WithTransientLifetime()
 .AddClasses(classes => (t => ("Service")))
  .AsImplementedInterfaces()
  .WithScopedLifetime());

summarize

Scrutor in real projects to simplify the configuration of dependency injection , especially in large projects , provides a flexible scanning and registration mechanism , making service registration more concise and maintainable .

Welcome to my public number "Net Share", technical articles are tweeted first and updated as they come , sharing details that you may not notice.

Warehouse Address:/khellang/Scrutor