Using Events Delegates in multi tenant web application

∥☆過路亽.° 提交于 2019-12-20 02:56:05

问题


I'm developing a multi tenant n-tier web application using asp.net Mvc 5.

In my service layer I am defining custom events for every important action and raising these events once these actions are executed. For example

Public event EventHandler EntityCreated;

Public void Create(Entity item) {
  Save(item);
  ......
  EntityCreated(this, item);
}

I intend on hooking up business rules and notifications to these events. The main reason I want to use events is decoupling of the logic and easy plug-ability of more events handlers without modifying my service layer.

Question: Does it make sense using events and delegates in asp.net?

Most examples I find online are for win forms or wpf. I get the advantage when it comes to multithreaded applications. Also the events are defined once per form and are active for the lifetime of the form.

But in my case the events will be per http request. So is it an overhead defining these events?


回答1:


As others pointed out that pub/sub or event bus is one solution. Another solution is something like what you are trying to do here but make it more formal.

Let's take a specific example of creating a customer. You want to send a welcome email when a new customer is created in the application. The domain should only be concerned with creating the customer and saving it in the db and not all the other details such as sending emails. So you add a CustomerCreated event. These types of events are called Domain Event as opposed to user interface events such as button click etc.

When the CustomerCreated event is raised, it should be handled somewhere in the code so that it can do the needful. You can use an EventHandlerService as you mentioned (but this can soon becomes concerned with too many events) or use the pattern that Udi Dahan talks about. I have successfully used Udi's method with many DI Containers and the beauty of the pattern is that your classes remain SRP compliant. You just have to implement a particular interface and registration code at the application bootstrap time using reflection.

If you need further help with this topic, let me know and I can share with you the code snippets to make it work.




回答2:


I have implemented Udi Dahan's implementation as pointed out by @Imran but with a few changes.

My Events are being raised in a Service Layer and for that using a Static Class dint seem right. Also have added support for async/await.

Also going down the Events & Delegates path did work out but it just felt like an overhead to register the events per request.

I have blogged my solution here http://www.teknorix.com/event-driven-programming-in-asp-net



来源:https://stackoverflow.com/questions/27747294/using-events-delegates-in-multi-tenant-web-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!