我有一個 .net API,我的 Program.cs 已經開始變得非常臃腫,有以下內容:
.
.
.
//core mappers
builder.Services.AddSingleton<IAppData_Mapper, AppData_Mapper>();
builder.Services.AddSingleton<IUserData_Mapper, UserData_Mapper>();
//pylon export services
builder.Services.AddTransient<IPylonItemExportService, PylonItemExportService>();
builder.Services.AddTransient<IPylonContactExportService, PylonContactExportService>();
//pylon repositories
builder.Services.AddSingleton<IPylonContactRepository, PylonContactRepository>();
builder.Services.AddSingleton<IPylonConnectionRepository, PylonConnectionRepository>();
builder.Services.AddSingleton<IPylonItemRepository, PylonItemRepository>();
builder.Services.AddSingleton<IPylonContactExportRepository, PylonContactExportRepository>();
builder.Services.AddSingleton<IPylonItemExportRepository, PylonItemExportRepository>();
builder.Services.AddSingleton<IPylonDocumentRepository, PylonDocumentRepository>();
builder.Services.AddSingleton<IPylonCentLineRepository, PylonCentLineRepository>();
builder.Services.AddSingleton<IPylonComEntryRepository, PylonComEntryRepository>();
builder.Services.AddSingleton<IPylonSupplierRepository, PylonSupplierRepository>();
builder.Services.AddSingleton<IPylonCustomerRepository, PylonCustomerRepository>();
//pylon sync services
builder.Services.AddTransient<IPylonItemSyncService, PylonItemSyncService>();
builder.Services.AddTransient<IPylonContactSyncService, PylonContactSyncService>();
builder.Services.AddTransient<IPylonMeasurementunitSyncService, PylonMeasurementunitSyncService>();
builder.Services.AddTransient<IPylonDocEntrySyncService, PylonDocEntrySyncService>();
builder.Services.AddTransient<IPylonCentLineSyncService, PylonCentLineSyncService>();
builder.Services.AddTransient<IPylonCommEntrySyncService, PylonCommEntrySyncService>();
builder.Services.AddTransient<IPylonCustomerSyncService, PylonCustomerSyncService>();
builder.Services.AddTransient<IPylonSupplierSyncService, PylonSupplierSyncService>();
.
.
.
將這些移出我的 program.cs 的最佳方法是什么?理想情況下,我希望他們在一個單獨的類中,該類將通過 Program.cs 呼叫
- 我可以將構建器傳遞給將添加服務的靜態方法嗎?
- 我可以創建服務陣列并執行 Services.AddRange 之類的操作嗎?
我對.net 上的 DI 架構相當陌生,任何指導方針都將不勝感激!
uj5u.com熱心網友回復:
builder要回答您的第一個問題,您可以通過創建一個新類并讓該方法接受并注冊服務然后回傳或創建一個擴展方法來將服務注冊移動到另一個類。創建擴展方法稍微“整潔”,您可以這樣做。
public static class MyServiceExtension
{
public static IServiceCollection AddMyServices(this IServiceCollection services)
{
// add your services
return services;
}
}
現在Program.cs你要做的就是。
builder.Services.AddMyServices();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/446779.html
上一篇:如何在不訴諸.ToString()的情況下按含義比較兩個不同的列舉?
下一篇:如何將Json檔案作為端點訪問?
