介紹
在ASP.NET Core中,每當(dāng)我們將服務(wù)作為依賴項注入時,都必須將此服務(wù)注冊到ASP.NET Core依賴項注入容器。但是,一個接一個地注冊服務(wù)不僅繁瑣且耗時,而且容易出錯。因此,在這里,我們將討論如何動態(tài)地一次注冊所有服務(wù)。
讓我們開始吧!
為了動態(tài)注冊所有服務(wù),我們將使用AspNetCore.ServiceRegistration.Dynamic?庫。這是一個很小但非常有用的庫,使您可以在不公開服務(wù)實現(xiàn)的情況下立即將所有服務(wù)注冊到ASP.NET Core依賴注入容器中。
現(xiàn)在,首先將最新版本的AspNetCore.ServiceRegistration.Dynamic?nuget軟件包安裝到您的項目中,如下所示:
Install-Package AspNetCore.ServiceRegistration.Dynamic
現(xiàn)在,讓您的服務(wù)繼承任何ITransientService,IScoperService和ISingletonService標(biāo)記接口,如下所示:
// 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
};
}
現(xiàn)在在您ConfigureServices的Startup類方法中:
public void ConfigureServices(IServiceCollection services)
{
services.RegisterAllTypes(); // This will register all the
// Scoped services of your application.
services.RegisterAllTypes(); // This will register all the
// Transient services of your application.
services.RegisterAllTypes(); // This will register all the
// Singleton services of your application.
services.AddControllersWithViews();
}
在AspNetCore.ServiceRegistration.Dynamic.Extensions名稱空間中RegisterAllTypes是可用的。
結(jié)論
僅此而已!任務(wù)完成!像上面一樣簡單,可以一次將所有服務(wù)動態(tài)注冊到ASP.NET Core Dependency Injection容器中。如果有任何問題,可以將其提交到該庫的Github存儲庫。您會盡快得到幫助。
.NET/.NET Core Dynamic Service Registration:
?https://github.com/TanvirArjel/TanvirArjel.Extensions.Microsoft.DependencyInjection
?????