views:

95

answers:

4

I have gallery in my project. I save images on the hard drive but tags, descriptions, etc. I save to the database. Working with the database and data validation going through the service layer. Since the user has remove the image, the files will be removed from the hard drive and the record will be removed from database.

//Action 
public ActionResult Delete (int id) 
( 
var entity = ServiceLayer.Entities.Get (id); 

System.IO.File.Delete (entity.FileName); //Might it be also be put to the service layer?
ServiceLayer.Entities.Delete (entit); 

return RedirectToAction ( "Index"); 
)

Is it better to put the code for deleting files in the service level or controller?

A: 

I would put that on the service layer so that you can abstract it and test it with TDD.

Daniel A. White
you can't test with TDD, you can do TDD, which is a different story.
Mikeon
A: 

You need to ask yourself a qustion, what is my controller responsible for?

IMHO, controllers should act as mediators between the View and the Model, where Model in this case includes Services.

That said, there are never strict rules on where to put what. Unlike zealots posting strict answers, I would take the pragmatic approach. Will adding file system dependancy to your database service make it more useful? Will it result with type explosion - your service would need to have the file system dependency injectet == +1 interface +1 concrete implementation +1 test class in case of unit tests etc.

Somtiems it's not worth it, so use you own judgement.

Mikeon
+1  A: 

You should always put this sort of code in a service.

The controller should do as little as possible - it should know how to get the service, pass it any parameters and return a view.

Even though the code is simple at present, it may grow over time, and this is a good way to ensure you have a good structure to begin with.

Daniel Robinson
and violates YAGNI principle amongst other things...ALWAYS is such a strong word.
Mikeon
Fair enough, I agree that using the term 'always' is a bit much. I like to say always in this situation because it's nice to have consistent coding standards in your application. It depends on your motivation for using the MVC pattern. If as you say it's a mediator between components, then you shouldn't put any other concerns in the controller.
Daniel Robinson
A: 

It's better to do that in the service layer.

Controller should only handle figuring out what user requested, calling required services to get done what the user wanted, and showing the user what they should see in response.

çağdaş