错误:"值不能为空。参数名称:上下文 ASP.NET MVC



我正试图从依赖项注入访问_context,但收到错误消息:

'值不能为null。参数名称: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);
}  

上面的dependency注入不起作用,但是如果我使用以下代码,它可以使用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中使用依赖项注入有点陌生,我的问题可能是什么?

Microsoft在ASP.NET Core 1(也称为ASP.NET MVC 6(中引入了IServiceCollection。它自己的依赖注入库随框架一起提供。

在MVC 6之前,在MVC 5中,我们可以使用外部依赖注入库,如unityautofacninject

内联是一个关于如何在ASP.NET MVC 5 中使用统一ioc容器的示例

  • 'Unity'Nuget包安装到您的项目中。

  • 将自定义类型添加到容器中。

  • 为具有统一容器对象的IDdependencyResolver接口提供一个实现,并将其分配给HttpConfiguration对象的DependencyResolver。

    public void ConfigureAuth(IAppBuilder app)
    {
    var config = new HttpConfiguration();
    var unityContainer = new UnityContainer();
    unityContainer.RegisterType<ApplicationDbContext>();
    config.DependencyResolver = new UnityResolver(unityContainer);
    //More code
    app.UseWebApi(config);
    }
    public class UnityResolver : IDependencyResolver
    {
    protected IUnityContainer container;
    public UnityResolver(IUnityContainer container)
    {
    if (container == null)
    {
    throw new ArgumentNullException("container");
    }
    this.container = container;
    }
    public object GetService(Type serviceType)
    {
    try
    {
    return container.Resolve(serviceType);
    }
    catch (ResolutionFailedException)
    {
    return null;
    }
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
    try
    {
    return container.ResolveAll(serviceType);
    }
    catch (ResolutionFailedException)
    {
    return new List<object>();
    }
    }
    public IDependencyScope BeginScope()
    {
    var child = container.CreateChildContainer();
    return new UnityResolver(child);
    }
    public void Dispose()
    {
    Dispose(true);
    }
    protected virtual void Dispose(bool disposing)
    {
    container.Dispose();
    }
    }
    

有了Unity容器,就可以去掉app.CreatePerOwinContextcreate方法。

最新更新