This article is a mirror article of machine translation, please click here to jump to the original article.

View: 413|Reply: 0

[Tips] .NET/C# dependency injection service registration Scrutor tool

[Copy link]
Posted on 2025-9-4 09:37:00 | | |
Requirements: When the project is relatively large and the writing syntax is very standardized, when we add an interface, we need to manually add it in the IServiceCollection container, so that the interface can be injected into the constructor. The Scrutor tool is very convenient for us to add automatically according to our rule configuration.

Scrutor

Microsoft.Extensions.DependencyInjection for assembly scanning and decorating extensions.

Source code address:The hyperlink login is visible.

review

Looking back at the service registration, the three ways of singleton injection are as follows:

Service registration

Let's say you have a code structure like this:

Interface definitions
public interface IUserService { }
public interface IOrderService { }

Implementation class
public class UserService : IUserService { }
public class OrderService : IOrderService { }

before

Registration is required one by one, and the code is as follows:

Or write your own method and register it through reflection (In fact, Scrutor is also through reflection), as follows:

afterwards

Scrutor makes it very convenient to register assemblies scan, especially for automatically registering multiple service classes (e.g., UserService registered as IUserService). The package dependencies are as follows:

The code is as follows:

Interpretation:
  • . FromAssemblyOf<UserService>(): Specifies the assembly to scan.
  • . AddClasses(): Scans all classes in the assembly set.
  • . AsImplementedInterfaces(): Automatically registers interfaces for these classes as they are implemented.
  • . WithScopedLifetime(): Set the lifetime to Scoped, which can also be WithTransientLifetime() or WithSingletonLifetime().

(End)




Previous:.NET/C# converts PDFs to images based on ImageMagick, GhostScript
Next:Alibaba Cloud mounts OSS to the Linux system directory
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com