繁体   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