簡體   English   中英

asp.net核心-在應用啟動后創建類的實例

[英]asp.net core - create an instance of a class after the app started

我有一些應在應用啟動后實例化的類。 就我而言,某些控制器可以觸發事件,並且我希望EventPublisher到那時已經具有訂閱服務器。

class SomeEventHandler {
   public SomeEventHandler(EventPublisher publisher) {
      publisher.Subscribe(e => {}, SomeEventType);
   }
}

class SomeController : Controller {
   private EventPublisher _publisher;
   public SomeController(EventPublisher publisher) {
      _publisher = publisher;
   }
   [HttpGet]
   public SomeAction() {
      _publisher.Publish(SomeEventType);
   }
}

調用Publish方法時是否可以有SomeEventHandler的實例?

也許有更好的解決方案?

是的,請使用依賴注入,這將使您在控制器構造函數中獲得實例。

services.AddScoped<EventHandler, EventPublisher>();  or
services.AddTransient<EventHandler, EventPublisher>(); or 
services.AddSingleton<EventHandler, EventPublisher>();

有關DI的更多信息: https : //docs.microsoft.com/zh-cn/aspnet/core/fundamentals/dependency-injection? view = aspnetcore- 2.0

如果不將EventHandler作為控制器或EventPublisher內部的直接依賴EventPublisher ,則不能確保在調用Publish時創建實例,並且沒有偵聽器監聽事件。

因此,您需要確保在某個地方創建了處理程序。 我個人將在Startup的Configure方法中執行此操作,因為在此方法中很容易注入依賴項,這樣,將在應用程序啟動時立即創建一個實例:

public void Configure(IApplicationBuilder app, EventHandler eventHandler)
{
    // you don’t actually need to do anything with the event handler here,
    // but you could also move the subscription out of the constructor and
    // into some explicit subscribe method
    //eventHandler.Subscribe();

    // …
    app.UseMvc();
    // …
}

當然,只有將EventHandlerEventPublisher都注冊為單例依賴項時,這才有意義。

暫無
暫無

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

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