[英]Create a instance of IDataProtectionProvider asp.net core
[英]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();
// …
}
當然,只有將EventHandler
和EventPublisher
都注冊為單例依賴項時,這才有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.