In MVC, where does code for background tasks belong?
I'm using ASP.NET, but I'm sure this pertains to any (or most) MVC frameworks.
When a new web project is created, you get a basic folder/semantic structure for your code:
- Controllers (service requests from browsers)
- Models (store and manipulate data)
- Views (HTML pages)
- Content (static content
- S开发者_JAVA百科cripts (JavaScript)
- App_Data (database files)
That's fine, but what if I want to have code that runs separately of browser requests -- for example, maybe a request runs some code, but in another thread, and continues executing after the request is completed. Or if the code is just run periodically independent of a request altogether.
In my case, the code would work on data -- generating it, cleaning it up, etc -- which makes me think it should go in models. But it doesn't really "model" data, it just works on it in the background. Is there a semantic place for this kind of thing?
You could utilize queues here, such MSMQ, RabbitMQ and etc. Each request which needs to be off-loaded can be queued and an external service would pop items from the queue and start processing them one-by-one. The service itself could be a plain windows service, although you could probably use WCF here. You could even integrate workflow into it for more complex processing scenarios. I generally create a separate namespace called "services.servicename" for these types of projects.
EDIT: You're probably looking at 2 parts here. For something like this to work, you'd need a service to take requests from your application and add them to the queue. And another service to actually processes the queue. You're likely looking at 3 different projects in your solution to accomplish this. Now, i've done this with WCF before, so my suggestions are based on WCF technology. Here is how your project structure would look.
- MyCompany.Services.QueueRequest - Takes requests from your application.
- MyCompany.Services.QueueRequestContract - Provides a contract (interface) which allows your application to interface with your QueueRequest service.
- MyCompany.Services.QueueProcessor - Background processor.
Your QueueRequest service will be implementing interface in the QueueRequestContract namespace instead of its own. We do that so that we can reuse that contract in your application layer to communicate with the service. So it kind of looks like this.
Your app --> QueueRequestContract (IMyService) --> QueueRequest service (implements IMyService).
精彩评论