简体   繁体   English

asp.net核心-在应用启动后创建类的实例

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

I have some classes which should be instantiated after the app started. 我有一些应在应用启动后实例化的类。 In my case, some controller can trigger an Event and I want EventPublisher to already have Subscribers by that moment. 就我而言,某些控制器可以触发事件,并且我希望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);
   }
}

Is it possible to have an instance of SomeEventHandler by the time the Publish method is called? 调用Publish方法时是否可以有SomeEventHandler的实例?

Or maybe there are much better solutions? 也许有更好的解决方案?

Yes, use dependency injection and that will take care of getting you an instance in the controller constructor. 是的,请使用依赖注入,这将使您在控制器构造函数中获得实例。

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

More info about DI: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.0 有关DI的更多信息: https : //docs.microsoft.com/zh-cn/aspnet/core/fundamentals/dependency-injection? view = aspnetcore- 2.0

Without taking the EventHandler as a direct dependency inside the controller or the EventPublisher , you cannot be sure that an instance is created when you call Publish and that there is a handler listening to your event. 如果不将EventHandler作为控制器或EventPublisher内部的直接依赖EventPublisher ,则不能确保在调用Publish时创建实例,并且没有侦听器监听事件。

So you will need to make sure that the handler is created somewhere . 因此,您需要确保在某个地方创建了处理程序。 I would personally do this in the Startup's Configure method since it's very easy to inject dependencies there, and this way, an instance will be created right when the application starts: 我个人将在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();
    // …
}

Of course, this only makes sense when both the EventHandler and the EventPublisher are registered as singleton dependencies. 当然,只有将EventHandlerEventPublisher都注册为单例依赖项时,这才有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM