我想通过使用创建我的自定义服务userManager
。但我不知道如何访问dbContext
.
public static class UserManagerExtensions
{
public static async Task<IdentityResult> AddProfileAsync(this UserManager<ApplicationUser> userManager, UserProfileModel model)
{
// how to access to dbContext here???
if (await dbContext.SaveChangesAsync() > 0)
{
return IdentityResult.Success;
}
return IdentityResult.Failed();
}
}
用法:
public class UserController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public UserController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<IActionResult> Update(UserProfileModel model)
{
await _userManager.AddProfileAsync(model);
return View();
}
}
如何访问DbContext
静态类中的类?
谢谢!
您应该将其注入控制器,然后将其传递给您的方法:
public class UserController : Controller
{
private readonly DbContext _dbContext;
private readonly UserManager<ApplicationUser> _userManager;
public UserController(DbContext dbContext, UserManager<ApplicationUser> userManager)
{
_dbContext = dbContext;
_userManager = userManager;
}
public async Task<IActionResult> Update(UserProfileModel model)
{
await _userManager.AddProfileAsync(_dbContext, model);
return View();
}
}
这样,您就可以完全控制数据库上下文的来源以及它存在的生命周期。
如果你的目标是像你所说的那样实际创建一个服务,你应该这样做,而不是使用扩展方法。你可以这样做:
public class UserController : Controller
{
private readonly ProfileService _profileService;
public UserController(ProfileService profileService)
{
_profileService = profileService;
}
public async Task<IActionResult> Update(UserProfileModel model)
{
await _profileService.AddProfileAsync(model);
return View();
}
}
public class ProfileService
{
private readonly DbContext _dbContext;
private readonly UserManager<ApplicationUser> _userManager;
public ProfileService(DbContext dbContext, UserManager<ApplicationUser> userManager)
{
_dbContext = dbContext;
_userManager = userManager;
}
public async Task<IdentityResult> AddProfileAsync(UserProfileModel model)
{
// do stuff
if (await dbContext.SaveChangesAsync() > 0)
{
return IdentityResult.Success;
}
return IdentityResult.Failed();
}
}
并且不要忘记在Startup.ConfigureServices
使用中注册您的服务:
services.AddTransient<ProfileService>();
这样,您现在就有了一个实际的服务,它具有明确的依赖关系并且您可以对其进行正确的测试,并且您还将更多的逻辑移出您的控制器,这使得它更容易推理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句