簡體   English   中英

autofac 解決鍵值問題

[英]autofac resolve issue for keyed values

我目前正在開發一項功能,並在 Autofac 中添加了這樣的構建器代碼

builder.RegisterType<ILTLoPublisher<ScheduleUpdateEvent>>()
           .AsImplementedInterfaces()
           .InstancePerRequest()
           .Keyed<IILTLoPublisher<ScheduleUpdateEvent>>(AuditType.Schedule);

builder.RegisterType<ILTLoPublisher<ScheduleUpdatePart>>()
           .AsImplementedInterfaces()
           .InstancePerRequest()
           .Keyed<IILTLoPublisher<ScheduleUpdatePart>>(AuditType.Part);

builder.RegisterType<ILTLoPublisher<ScheduleUpdateTest>>()
           .AsImplementedInterfaces()
           .InstancePerRequest()
           .Keyed<IILTLoPublisher<ScheduleUpdateTest>>(AuditType.Test);

此代碼作為控制台應用程序服務運行,對此的調用是從 api 服務進行的。我希望它被如下調用


AutoFacModule autofac = new AutoFacModule();
            var builder = new ContainerBuilder();
            autofac.LoadBuilder(builder);
            Container = builder.Build();
            using (var scope = Container.BeginLifetimeScope())
            {
var _publisher1 = scope.ResolveKeyed<IILTLoPublisher<ScheduleUpdateEvent>>(AuditType.Schedule);

var _publisher2 = scope.ResolveKeyed<IILTLoPublisher<ScheduleUpdatePart>>(AuditType.Part);

var _publisher2 = scope.ResolveKeyed<IILTLoPublisher<ScheduleUpdateTest>>(AuditType.Test);
}

當我嘗試在我的實現 class 中使用以下代碼解決它時

var _publisher = scope.ResolveKeyed<IILTLoPublisher<ScheduleUpdateEvent>>(AuditType.Schedule);

我收到以下錯誤

Unable to resolve the type Apiconnector.Integrations.Vilt.Service.Providers.Custom.Publish.ILTLoPublisher`1[LMS.ILT.ScheduleUpdateEvent]' because the lifetime scope it belongs in can't be located

除非正在解決的 object 是 web 請求的一部分,否則您不能使用InstancePerRequest (如對問題的評論所述)。 進一步來說:

  • 執行的應用程序必須是 web 應用程序。
  • 執行應用程序需要有Autofac web 集成到位。
  • The resolution must be happening in that web application as part of a response to an inbound web request - for example, as part of an MVC controller or ASP.NET Core middleware.

“每個請求”語義與發出請求的客戶端無關 - 它與處理請求的服務器有關

您可能想花一些時間閱讀有關該主題的文檔。 那里有一節是關於如何為您的應用程序實現自定義的每個請求語義。

如果您正在創建的是一個接收來自客戶端的請求的控制台應用程序(例如,自托管的 web 應用程序),那么您需要:

  • Add the existing Autofac web integration for your app type (we do support ASP.NET Web API and ASP.NET Core self hosted scenarios); 或者
  • 如果您不使用 ASP.NET (請參閱我鏈接的那個文檔),請實現一些自定義。

如果您正在創建的是作為客戶端發出請求的控制台應用程序,那么您應該忽略InstancePerRequest 反而:

  • 圍繞每個請求(就像您正在做的那樣)創建一個新的生命周期 scope 並將其視為一個工作單元。
  • 將組件注冊為InstancePerLifetimeScope ,以便在該生命周期 scope 期間只有一個。

也就是說,如果沒有最少的復制,就很難看到你在做什么,以提供任何形式的指導。

由於您提到您對這一切都很陌生,因此非常值得您花時間查看Autofac 文檔以開始理解此類概念,並查看示例存儲庫,其中有許多不同應用程序類型的工作示例可供展示你是如何工作的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM