我想將控制器創建為服務,并另外手動創建它們。
為此,我在“Startup”類中添加了一些代碼,我的“ConfigureServices”方法以:
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.AddControllers()
.AddControllersAsServices()
.AddNewtonsoftJson();
...
AddControllersAsServices據說切換到控制器作為具有瞬態生命周期的服務。知道了這一點,我補充說:
...
services.AddTransient<MyController>(sp =>
{
return new MyController(
sp.GetService<ILogger>(),
sp.GetService<Microsoft.AspNetCore.Authorization.IAuthorizationService>(),
...
});
但是當我嘗試運行它時,我在 IHostBuilderBuild方法呼叫(在“Program.cs”中)出現錯誤:
'某些服務無法構造(驗證服務描述符時出錯'ServiceType:MyController Lifetime:Transient ImplementationType:MyController':找不到適合型別'MyController'的建構式。確保型別是具體的并且服務已注冊對于公共建構式的所有引數。)'
執行了“AddTransient”呼叫,但它的主體——不,從錯誤訊息來看,它看起來系統依賴于經典 DI,而不是我直接提供的條目。
那么如何強制使用我定義的條目呢?
uj5u.com熱心網友回復:
好的,最后我找到了它:https ://github.com/dotnet/aspnetcore/issues/27959就在呼叫Build“IHostBuilder”之前,必須呼叫:
.UseDefaultServiceProvider((context, options) =>
{
options.ValidateOnBuild = false;
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/414092.html
標籤:
下一篇:使用serilog保存日志記錄
