【发布时间】:2020-07-13 15:20:37
【问题描述】:
我正在尝试从依赖注入中访问 _context,但是我收到了错误消息:
'值不能为空。参数名称:context'
我在AdminController.cs中有以下内容:
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Threading.Tasks;
namespace GuildCars.UI.Controllers
{
public class AdminController : Controller
{
private readonly ApplicationDbContext _context;
public AdminController(ApplicationDbContext context)
{
_context = context;
}
public AdminController() { }
...
public ActionResult EditUser(string id)
{
var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context)); //fail to get _context.
var appUser = userMgr.FindById(id);
//var appUser = userMgr.FindByEmail(email);
var user = new UserEditViewModel
{
UserID = appUser.Id,
FirstName = appUser.FirstName,
LastName = appUser.LastName,
Email = appUser.Email,
Role = appUser.Role
};
return View(user);
}
我上面的依赖注入不起作用,但是如果我使用以下代码,它可以与 using 语句一起使用:
using (var ctx = new ApplicationDbContext())
{
ctx.Cars.Add(model.Car);
if (model.Car == null)
model.Car = new Car();
ctx.SaveChanges();
}
我检查了我的Startup.Auth.cs,确实有ApplicationDbContext.Create:
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
...
另外,我检查了 IdentityModels.cs 中是否有 Create() 方法,并且确实有。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<Car> Cars { get; set; }
public DbSet<Transaction> Transactions { get; set; }
public DbSet<BodyStyle> BodyStyles { get; set; }
public DbSet<ContactUs> ContactUs { get; set; }
public DbSet<ExteriorColor> ExteriorColors { get; set; }
public DbSet<InteriorColor> InteriorColors { get; set; }
public DbSet<Make> Makes { get; set; }
public DbSet<Model> Models { get; set; }
public DbSet<Specials> Specials { get; set; }
public DbSet<Transmission> Transmissions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
我对在 ASP.NET MVC 中使用依赖注入有点陌生,我的问题可能是什么?
【问题讨论】:
-
您是否使用服务注册器添加了dbcontext??
-
我不确定你的意思,我知道在 ASP.NET Core 中你的范围是
ConfigureServices。但这是 ASP.NET MVC,我不知道它是如何工作的。 -
dbcontext 不在
Startup.Auth.cs中,如果这是您要问的。我有 ApplicationDbContext。 -
如果这不是.net core,你使用的是哪个依赖注入库?您能否确保
ApplicationDbContext已在您的依赖注入配置中注册? -
好吧,我以为
app.CreatePerOwinContext(ApplicationDbContext.Create);正在注册我的依赖注入。有什么指南可以用来注册ApplicationDbContext吗?
标签: c# asp.net-mvc