当我在这个控制器的构造函数中设置断点时,我看到来自userManager.Users的System.ObjectDisposedException。为什么.NET会给我一个处理过的UserManager?我有其他控制器似乎以相同的方式设置,他们的UserManagers工作正常(这一个在它调用GetUserAsync时死亡)
[RequireHttps]
public class HomeController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RegionService _regionService;
private readonly ILogger _logger;
public HomeController(UserManager<ApplicationUser> userManager, RegionService regionService, ILoggerFactory loggerFactory)
{
_userManager = userManager;
_regionService = regionService;
_logger = loggerFactory.CreateLogger<HomeController>();
}
[HttpGet]
public async Task<IActionResult> Index()
{
var user = await _userManager.GetUserAsync(HttpContext.User);
...
}
...我不应该访问Home / Index中的数据库;之后我会改变它
编辑: 这就是配置服务的方式:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 6;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
services.AddTransient<RegionService>();
// require SSL
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
}
答案 0 :(得分:0)
问题出在我创建的一个名为RegionService
的类的构造函数中 public RegionService(IServiceProvider serviceProvider)
{
using (var context = serviceProvider.GetService<ApplicationDbContext>())
{
...
}
}
使用&#39;声明原因&#39; context&#39;在完成该代码块之后处理。我应该刚刚制作了一个可以处理的DbContext的新实例:
public RegionService(IServiceProvider serviceProvider)
{
using (var context = new ApplicationDbContext(
serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
{
...
}
}