介紹
在ASP.NET Core中,每當(dāng)我們將服務(wù)作為依賴項(xiàng)注入時(shí),都必須將此服務(wù)注冊(cè)到ASP.NET Core依賴項(xiàng)注入容器。但是,一個(gè)接一個(gè)地注冊(cè)服務(wù)不僅繁瑣且耗時(shí),而且容易出錯(cuò)。因此,在這里,我們將討論如何動(dòng)態(tài)地一次注冊(cè)所有服務(wù)。
讓我們開始吧!
為了動(dòng)態(tài)注冊(cè)所有服務(wù),我們將使用AspNetCore.ServiceRegistration.Dynamic?庫(kù)。這是一個(gè)很小但非常有用的庫(kù),使您可以在不公開服務(wù)實(shí)現(xiàn)的情況下立即將所有服務(wù)注冊(cè)到ASP.NET Core依賴注入容器中。
現(xiàn)在,首先將最新版本的AspNetCore.ServiceRegistration.Dynamic?nuget軟件包安裝到您的項(xiàng)目中,如下所示:
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ù)完成!像上面一樣簡(jiǎn)單,可以一次將所有服務(wù)動(dòng)態(tài)注冊(cè)到ASP.NET Core Dependency Injection容器中。如果有任何問題,可以將其提交到該庫(kù)的Github存儲(chǔ)庫(kù)。您會(huì)盡快得到幫助。
.NET/.NET Core Dynamic Service Registration:
?https://github.com/TanvirArjel/TanvirArjel.Extensions.Microsoft.DependencyInjection
?????