【问题标题】:asp.net core - create an instance of a class after the app startedasp.net core - 在应用启动后创建一个类的实例
【发布时间】:2018-04-24 06:55:45
【问题描述】:

我有一些类应该在应用程序启动后实例化。在我的例子中,一些控制器可以触发一个事件,我希望 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 的实例?

或者也许有更好的解决方案?

【问题讨论】:

    标签: c# asp.net-core instance publish-subscribe


    【解决方案1】:

    是的,使用依赖注入,这将负责在控制器构造函数中为您获取一个实例。

    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

    【讨论】:

    • 我理解,但我不确定这是在控制器中拥有此类实例的好方法,因为它从未在那里使用过。
    • 是的,所以如果您在控制器中根本不使用它,请将其移除。
    • @poke,我使用的是EventPublisher 而不是SomeEventHandler。我希望在调用 Publish 时创建 SomeEventHandler 实例。
    • 很抱歉让您感到困惑。我已经用类的正确属性编辑了我的问题。
    • @E.Shcherbo:将其添加到您的 DI 容器中,并在它的构造函数中使用也已添加到 DI 容器中的 EventPublisher
    【解决方案2】:

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

    【讨论】:

    • 我知道了。非常感谢!
    猜你喜欢
    • 2018-01-05
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 2018-11-02
    相关资源
    最近更新 更多