im working in a personal project in MVC core 2.1, reading about N-tier layers I apply the follow pattern (I simplified the code):
My DBContext:
public class CRUDContext : DbContext, IDisposable
{
public CRUDContext(DbContextOptions<CRUDContext> options) : base(options)
{
}
public DbSet<User> User { get; set; }
}
My class (the Base Entity have the default fields like ID, createdDate etc)
public class User : BaseEntity
{
public string UserName { get; set; }
}
Startup:
services.AddScoped<UserBL>();
Controller inject as DI with other BL classes:
protected readonly UserBL _userBL;
protected readonly StateBL _stateBL;
protected readonly UserTypeBL _userTypeBL;
public UsersController(UserBL userBL,StateBL stateBL,UserTypeBL userTypeBL)
{
_userBL = userBL;
_stateBL = stateBL;
_userTypeBL = userTypeBL;
}
In my BL, Its create a instance of a baseBL
public class UserBL : BaseBL<User>
{
#region Contructor
private readonly CRUDContext _context;
public UserBL(CRUDContext context, ILogger<User> logger = null) : base(context)
{
_context = context;
}
#endregion
#region Metodos Locales
public async Task<bool> UserExistsAsync(String UserName)
{
try
{
return !await _context.User.AnyAsync(e => e.UserName == UserName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error UserExistsAsync");
return false;
}
}
}
and in my BaseBL I have all the basic operations like selectable, getbyID , so only overwrite when is necessary for business logic.
MY QUESTIONS:
Which is better ?
- Pass a context thru the controller to the BL so only instance of the controller is user for the whole application.
- Create a separate DBcontext in each BL so they can handle their request separately.
Sometimes I get this error: "A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.". Is because im using the same DB context?
Is good idea to use Async methods for basics operations like getById and SelectAll in my BaseBL method?
I hope I made myself clear and thanks in advance...
Aucun commentaire:
Enregistrer un commentaire