asp.net 核心 - 在应用程序启动后创建一个 class 的实例

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/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.0

如果不将 EventHandler 作为控制器或 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 都注册为单例依赖项时才有意义。