Where to put generic classes in ASP.NET MVC
Posted on 2015-02-13
I know similar questions have been asked on various forums, but I want to ask this a little more specifically:
When writing an ASP.NET MVC application, what's the best practice for where to include classes that don't strictly fit into the MVC model?
In my understanding, the view plays a similar role to the ASPX page in WebForms, except of course with special routing logic, etc. The controller plays a similar role to the code-behind page...that is, there's built-in logic that connects controllers to page requests (e.g., that causes the controller to execute following a given URL request). And the model is supposed to play the role of classes that expose data from the database or other data source....so whereas in an old-fashioned application, people would create maybe a "person" object and a "company" object, and whatever, with properties read from the database, now these classes all go in the model.
The issue is that typically, there are always going to be classes that don't correspond to a page request or to a database object. For example, maybe there's a singleton class to handle errors and logging, or maybe there's one to store certain constant values, or one to get certain things from appSettings that are used a lot in the application, or maybe one that processes some specific business logic that really isn't linked to a page request, as it could possibly be called through several different paths.
In reading various forums, I've seen a few different viewpoints:
(1) Put these into a separate libraries (e.g., different projects), so they're compiled in their own dll files.
(2) Just throw these into the model anyway, even if they don't really fit (or maybe just sort of fit in that they have properties which could be classified as "data").
(3) If a class's main use is as a "verb" rather than a "noun," then try to fit it into the controller paradigm, even though it doesn't fit there either.
(4) Create a new folder and namespace, and call it something.
As to (1), I see that could work well for utility functions that one may want to include in multiple projects. But in other situations, it may create too many dependencies back to the main project, passing lots of data through parameters, doing callbacks, and basically making things over-complicated.
(2) seems reasonable to me. But I'm still wondering if maybe it's abusing the model folder/namespace too much.
(3) seems way off, because the controller logic is very particular, so it doesn't seem appropriate for generic classes.
(4) seems reasonable, but it's kind of like admitting that MVC is broken in some way and needs one to add to it. Plus, it means that people need to look into more folders to find where the code is.
In any case, just wondered people's opinions about this. I know there's maybe no single clear answer, but I'm trying to understand better what's ideal for this kind of situation.