I am implementing repository patter and I have a doubt about which code is better in terms of standards and good practices.
This is for an MVC 5 project I am starting, with repository patter in mind.
This is the first approach: I am using a connstructor to set de db context and inside each method I use using
public class EmployeeRepository : IEmployeeRepository
{
private DBModel contextBD;
public EmployeeRepository(DBModel contextBD)
{
this.contextBD = contextBD;
}
public async Task<bool> Add(Employee employee)
{
using (contextBD)
{
contextBD.Employee_Table.Add(new Employee_Table()
{
LLP_Id = employee.id,
Name = employee.name,
});
await contextBD.SaveChangesAsync();
}
return true;
}
}
The second approach is this: I do not use a constructor, and set the context in the using block
public class EmployeeRepository : IEmployeeRepository
{
public async Task<bool> Add(Employee employee)
{
using (DBModel contextBD = new DBModel())
{
contextBD.Employee_Table.Add(new Employee_Table()
{
LLP_Id = employee.id,
Name = employee.name,
});
await contextBD.SaveChangesAsync();
}
return true;
}
}
Which one will work better, which is the best practice and why, what are the benefits of unis one or another.
In the first example, since you IoC inject it, you shouldn't wrap it in a using statement since this instance would be used by all methods for this call. (Assuming its IoC injected.)
While the 2nd option would work, you can't do any unit testing since it is now hard-coded.
I would recommend a third option. I would inject a ContextFactory. It would look something like this:
public class EmployeeRepository : IEmployeeRepository
{
private IDBModelFactory factory;
public EmployeeRepository(IDBModelFactory factory)
{
this.factory = factory
}
public async Task<bool> Add(Employee employee)
{
using (var contextBD = factory.Create())
{
contextBD.Employee_Table.Add(new Employee_Table()
{
LLP_Id = employee.id,
Name = employee.name,
});
await contextBD.SaveChangesAsync();
}
return true;
}
}
In this case, the Create()
method implementation would just return new DBModel()
and now you are good to go!