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.
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?
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
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.
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.