Kuttan Sujith
Kuttan Sujith

Reputation: 7979

BackgroundWorker in MVC pattern

public ActionResult Index()
{    
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(Domail);
    bw.RunWorkerAsync();
    Return View();
}

private void Domail(object sender, DoWorkEventArgs e)
{
    MyStaticClassToSendMail.MailIt(); 
}

I am planning to have the above lines in my MVC Controller,

The syntax object sender, DoWorkEventArgs e reminds me of the old ASP.NET web applications.

So my question here is: Does doing this break any pattern? Is it legal to do in MVC?

Upvotes: 1

Views: 5254

Answers (2)

Chandu
Chandu

Reputation: 1042

doing this break any Pattern?

Yes it's breaking the MVC pattern. The way you have presented code is not a good idea in MVC. In MVC you need to separate Model View and Controller

Model Contains both business logic as well as data logic, but in you case you have written Business logic in controller. And It will give output.

But in real time it's difficult to maintain.

So separate business logic into a model and access that in the controller.

Upvotes: 2

James R.
James R.

Reputation: 840

I don't know that it breaks the rules, but I would prefer a more robust design, especially if you do a lot of background operations. I.e., separate out any background tasks into a process other than the "realtime" web application.

  1. Web application simply queues up the task (in this case, a SendEmailTask) into a background task queue, such as a database table called BackgroundTasks.
  2. A task processor, hosted in something such as a Windows Service perioidically polls the task queue and processes the outstanding tasks.

This provides

  1. Reduced risk that the web application will be slow to respond to user input.
  2. Control and visibility into the system's functioning (the queue can be a record of what took place).
  3. Ability to retry failed tasks transparently or as needed manually.
  4. Ability to distribute the task processing.

Windows provides queueing functioinality (the name escapes me at the moment), but it is somewhat awkward to deal with IMO. I prefer using a simple DB table for my queue implementation. You can encode the task messages into a column using XML, for example. The task processing service can be used for all types of tasks, not just emailing. For example, you might need a task that post-authorizes a CC transaction after an item is marked shipped by your WMS system.

Upvotes: 1

Related Questions