【问题标题】:Error: 'Value cannot be null. Parameter name: context' ASP.NET MVC错误:'值不能为空。参数名称:上下文' ASP.NET MVC
【发布时间】: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


【解决方案1】:

Microsoft 在 ASP.NET Core 1(又名 ASP.NET MVC 6)中引入了 IServiceCollection。它是框架自带的依赖注入库。

在 MVC 6 之前,在 MVC 5 中我们可以使用外部依赖注入库,例如 unity、autofac 或 ninject。

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

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

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

  • 为 IDependencyResolver 接口提供统一容器对象的实现,并将其分配给 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.CreatePerOwinContext 和 create 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-09
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    相关资源
    最近更新 更多