ASP.NET Core依赖注入容器中的动态服务注册

跟着阿笨一起玩NET

共 1633字,需浏览 4分钟

 · 2022-03-18

介绍

ASP.NET Core中,每当我们将服务作为依赖项注入时,都必须将此服务注册到ASP.NET Core依赖项注入容器。但是,一个接一个地注册服务不仅繁琐且耗时,而且容易出错。因此,在这里,我们将讨论如何动态地一次注册所有服务。

让我们开始吧!

为了动态注册所有服务,我们将使用AspNetCore.ServiceRegistration.Dynamic 库。这是一个很小但非常有用的库,使您可以在不公开服务实现的情况下立即将所有服务注册到ASP.NET Core依赖注入容器中。

现在,首先将最新版本的AspNetCore.ServiceRegistration.Dynamic nuget软件包安装到您的项目中,如下所示:

Install-Package AspNetCore.ServiceRegistration.Dynamic

现在,让您的服务继承任何ITransientServiceIScoperServiceISingletonService标记接口,如下所示:

  1. // Inherit `IScopedService` interface if you want to register `IEmployeeService`

  2. // as scoped service.

  3. public class IEmployeeService : IScopedService

  4. {

  5. Task CreateEmployeeAsync(Employee employee);

  6. }


  7. internal class EmployeeService : IEmployeeService

  8. {

  9. public async Task CreateEmployeeAsync(Employee employee)

  10. {

  11. // Implementation here

  12. };

  13. }

现在在您ConfigureServicesStartup类方法中:

  1. public void ConfigureServices(IServiceCollection services)

  2. {

  3. services.RegisterAllTypes(); // This will register all the

  4. // Scoped services of your application.

  5. services.RegisterAllTypes(); // This will register all the

  6. // Transient services of your application.

  7. services.RegisterAllTypes(); // This will register all the

  8. // Singleton services of your application.


  9. services.AddControllersWithViews();

  10. }

AspNetCore.ServiceRegistration.Dynamic.Extensions名称空间中RegisterAllTypes是可用的。

结论

仅此而已!任务完成!像上面一样简单,可以一次将所有服务动态注册到ASP.NET Core Dependency Injection容器中。如果有任何问题,可以将其提交到该Github存储库。您会尽快得到帮助。

.NET/.NET Core Dynamic Service Registration:

 https://github.com/TanvirArjel/TanvirArjel.Extensions.Microsoft.DependencyInjection


     

浏览 11
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报