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

 

介绍

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

让我们开始吧!

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

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

Install-Package AspNetCore.ServiceRegistration.Dynamic

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

// Inherit `IScopedService` interface if you want to register `IEmployeeService` 
// as scoped service.
public class IEmployeeService : IScopedService 
{
    Task CreateEmployeeAsync(Employee employee);
}

internal class EmployeeService : IEmployeeService
{
   public async Task CreateEmployeeAsync(Employee employee)
   {
       // Implementation here
   };
}

现在在您ConfigureServicesStartup类方法中:

public void ConfigureServices(IServiceCollection services)
{
   services.RegisterAllTypes<IScopedService>();    // This will register all the 
                                                   // Scoped services of your application.
   services.RegisterAllTypes<ITransientService>(); // This will register all the 
                                                   // Transient services of your application.
   services.RegisterAllTypes<ISingletonService>(); // This will register all the 
                                                   // Singleton services of your application.

   services.AddControllersWithViews();
}

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

结论

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值