Understanding Separation Of Concern in ASP.NET MVC

What is Separation of Concern?

Wikipedia says “In computer science, separation of concerns (SoC) is a design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. A concern is a set of information that affects the code of a computer program.”

As said concern is a set of information, in our application concern is known as modules or a set of responsibility, we use this principle to separate application module to manage scalable applications.

You can also think of separation the same as how we use layers in our application as follows:

ui

However we can implement different tiers for databases as well.

The above architecture can be followed in any web or native (desktop) application, in order to use separation of concern.

How separation of concern in ASP.NET

A couple of years ago, Microsoft came up with ASP.NET MVC which is a superset of ASP.NET (now ASP.NET web form). Since before ASP.NET MVC there was Spring (JAVA), Ruby on Rail frameworks and may be others has already implemented MVC architecture.

ASP.NET MVC adds SoC for web (http) and separate Model (business), View(User Interface) and Controller (Processing data to view or vice versa), it gives responsibility to Model, View, Controller as follows :

mvc

You may have seen the above diagram in many articles. Herethe model is responsible to handle business logic, don’t get it confused with ViewModel as ViewModel are simple classes in ASP.NET MVC to bind strongly typed views.

Flexibility and its violation of SoC in ASP.NET MVC

As a ASP.NET MVC developer I feel it’s quite flexible to work with MVC as it’s a framework with extensibility as we can implement our own principles if required.

MVC framework uses loose coupling (another form of SoC) for every concern (modules). It’s recommended to use Model for business logic, controller for processing incoming requests and views to display information to end user.

But the actual problem is due to flexibility of ASP.NET MVC and it’s easy to violate these principles.

Examples of violation of MVC principle:

  1. Using ViewBag or ViewData for passing data from controller to view:
    1. // contoller  
    2. public ActionResult Index()   
    3. {  
    4.         ViewBag.EmployeeData = getEmplyees(x => x.DOB > DateTime.Now);  
    5.     }  
    6.     // view  
    7. foreach(var employee in ViewBag.EmployeeData)  
    8. {  
    9.     // using data  
    10. }  
    Above line of code doesn’t restrict developer, but it violates principle to use ViewModel to display data in view.

  2. Using business logic in controller:
    1. Public ActionResult Save(Employee model)  
    2. {  
    3.     If(ModelState.IsValid)   
    4.     {  
    5.         _dbContext.Employees.Add(model)  
    6.     }  
    7.     Return RedirectToAction(“Success”);  
    8. }  
    Using above code, its violation of SRP because controller is having database logic to save information.

  3. Using business logic in view:
    1. @if(user.Role == ”Admin”)  
    2. {  
    3.     //  
    4. }  
    5. Else   
    6. {  
    7.     //  
    8. }  
    Using this we are using business logic in view which is only responsible to display information.

Apart from these, there area lot of code snippets you can find in your ASP.NET MVC project as well as online communities.

Recommendations

Where to put business logic:

It’s recommended to use a Service layer to implement business logic in your application as follows:

  1. public class EmployeeService   
  2. {  
  3.     IRepository _employeeRepository;  
  4.     public EmployeeService(IRepository employeeRepository)   
  5.     {  
  6.         this._employeeRepository = employeeRepository;  
  7.     }  
  8.     public IEnumeratble < Employee > GetEmplyee(int id)   
  9.     {  
  10.         return _employeeRepository.FindBy(x => x.ID == id).FirstOrDefault();  
  11.     }…………..  
  12. }  
Repository pattern is a well known pattern for data access, here is a sample:
  1. public class Repository < T > : IRepository < T > where T: class   
  2. {  
  3.     private DbContext Context;  
  4.   
  5.     public Repository(DbContext ctx)   
  6.     {  
  7.         Context = ctx;  
  8.     }  
  9.   
  10.     public virtual IQueryable < T > GetAll()   
  11.     {  
  12.         IQueryable < T > query = Context.Set < T > ().AsQueryable();  
  13.         return query;  
  14.     }  
  15.     public IQueryable < T > FindBy(System.Linq.Expressions.Expression < Func < T, bool >> predicate)   
  16.     {  
  17.         IQueryable < T > query = Context.Set < T > ().Where(predicate);  
  18.         return query;  
  19.     } 
  20.   
  21. }  
Repository can be wrapped with a unit of work to save final changes all together. Here is sample unit of work interface which can be implemented for convenience, however it’s not required.
  1. public interface IUnitOfWork  
  2. {  
  3.     IRepository < TEntity > GetRepository < TEntity > () where TEntity: class;  
  4.     void Save();  
  5. }  
And finally we can inject (using DI) service in controller to use business objects.
  1. public class EmployeeContoller   
  2. {  
  3.     IService _employeeService;  
  4.     Public EmployeeContoller(IService employeeService)   
  5.     {  
  6.         _employeeService = employeeService;  
  7.     }…………  
  8. }  
I hope readers will avoidthe  above mentioned mistakes while working with ASP.NET MVC to deliver scalable applications.
 
Read more articles on ASP.NET MVC:

 


Similar Articles