【发布时间】:2018-05-12 13:23:27
【问题描述】:
我有三个程序集,一个模型程序集、一个 DAL 程序集和我的 BLL 程序集。 现在我想注册一个用户,在我的 BLL 程序集中调用一个控制器,并为 DALL 程序集中的一个类准备好数据,以便将数据添加到数据库中。
问题是,在我的 DAL 类中,我使用了我的 dbcontext 和身份中的 usermanager 类。现在,当我想实例化我的 DALL 类时,我需要传递 dbcontext 和 usermanager,这意味着我需要在我的控制器中实例化 dbcontext 和 usermanager,以便将它们传递给我的 DALL 类。
所以我的问题是:有没有一种简洁的方法来调用我的 DALL 类,而无需在我的控制器中实例化数据只是为了将它传递给我的 DALL 类。
我的控制器
public class UserController : Controller
{
private ApplicationDbContext _context;
private IPasswordHasher<ApplicationUser> _passwordHasher;
private UserManager<ApplicationUser> _userManager;
private ApplicationUserStore _userStore;
public UserController(ApplicationDbContext _context, IPasswordHasher<ApplicationUser> passwordHasher, UserManager<ApplicationUser> userManager)
{
_passwordHasher = passwordHasher;
_userManager = userManager;
_userStore = new ApplicationUserStore(_context, _userManager);
}
[AllowAnonymous]
[HttpPost("create")]
public async Task<IActionResult> Create([FromBody] CreateApplicationUserViewModel model)
{
var user = new ApplicationUser()
{
Email = model.Email,
UserName = model.Email,
FirstName = model.FirstName,
LastName = model.LastName
};
var result = await _userStore.Create(user);
if (result.Succeeded)
{
try
{
_passwordHasher.HashPassword(user, model.ConfirmPassword);
return Ok();
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError("error", error.Description);
}
return BadRequest(result.Errors);
}
我的 DALL 课程
public class ApplicationUserStore
{
private ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public ApplicationUserStore(ApplicationDbContext ctx, UserManager<ApplicationUser> userManager)
{
_context = ctx;
_userManager = userManager;
}
public async Task<ApplicationUser> Get(string id)
{
return await _context.Users.Where(u => u.Id == id).SingleOrDefaultAsync();
}
public async Task<IdentityResult> Create(ApplicationUser user)
{
return await _userManager.CreateAsync(user);
}
}
在此先感谢
【问题讨论】:
-
如果是asp.net core,为什么不用内置DI?
标签: c# asp.net .net asp.net-core-2.0