I am creating a demo project which contains crud operations using a repository pattern and dependency injection.
This is my structure:
Approach 1 (very popular, used by many developers)
My repository interface:
public partial interface IRepository<T>
{
void Insert(T entity);
}
My service layer:
public partial interface IEmployeeService
{
void InsertCategory(EmployeeMaster employeeMaster);
}
My class which will implement that interface (service):
public partial class EmployeeService : IEmployeeService
{
private readonly IRepository<EmployeeMaster> _employeeMasterRepository;
public EmployeeService(IRepository<EmployeeMaster> employeeMasterRepository)
{
this._employeeMasterRepository = employeeMasterRepository;
}
public virtual void InsertCategory(EmployeeMaster employeeMaster)
{
_employeeMasterRepository.Insert(employeeMaster);
}
This is my controller:
public class HomeController : Controller
{
private readonly IEmployeeService _employeeService;
public HomeController(IEmployeeService employeeService)
{
this._employeeService = employeeService;
}
Above is the structure which I am following from Nop Commerce project (http://www.nopcommerce.com) and I think most developers now a days are following this structure only that is repository pattern and dependency injection.
Previously I was doing like Below like making one Bal(business Access layer) project in my application and then making class file in Bal and doing insert like below:
Approach 2:
public class MyBal()
{
public void Insert()
{
using (MyEntities context = new MyEntities ())
{
var result = context.MyTable.Add(_MyTable);
context.SaveChanges();
return result;
}
}
And then Calling this Method straight Away from My Mvc application like this:
[HttpPost]
public ActionResult Insert(Model M)
{
MyBal bal = new MyBal ();
bal.Insert();
}
So why most of the developers go on creating such a complex structure that is repository pattern.Can anybody explain me the difference between Approach 1 and Approach 2 ??
Does Approach 1 increases performance or it is just related to separation of code or better maintainability of code.