简体   繁体   English

数据存储库实例Null-NullReferenceException吗? 你调用的对象是空的

[英]Data Repository instance Null - NullReferenceException? Object reference not set to an instance of an object

Everything I've seen online, I'm supposed to instantiate an instance of my repo, which I believe I have done yet I'm still getting a null reference exception. 我在网上看到的所有内容,都应该实例化我的仓库的实例,我相信我已经完成了,但是我仍然收到空引用异常。

Here's the class which implements the IArticleRepository interface. 这是实现IArticleRepository接口的类。

public class ArticleRepository : IArticleRepository
    {
        private readonly ApplicationDbContext dbContext;
        public ArticleRepository(ApplicationDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public void DeleteArticle(int articleId)
        {
            throw new NotImplementedException();
        }

        public async Task<Article> GetArticleAsync(int articleId)
        {
            Article article = await dbContext.Articles.FirstOrDefaultAsync(x => x.Id == articleId);
            return article;
        }

        public async Task<IEnumerable<Article>> GetArticles()
        {
            var articles = await dbContext.Articles.ToListAsync();
            return articles;
        }

        public void InsertArticle(Article article)
        {
            dbContext.Articles.Add(article);
        }

        public async void Save()
        {
            await dbContext.SaveChangesAsync();
        }

        public void UpdateArticle(Article article)
        {
            throw new NotImplementedException();
        }
    }

In my controller, I have: 在我的控制器中,我有:

private readonly ArticleRepository _ArticleRepo;

public ArticleController(){}

public ArticleController(ArticleRepository _ArticleRepo)
{
    this._ArticleRepo = _ArticleRepo;
}

So I'm instantiating an instance of the ArticleRepo(hopefully I did this correct). 因此,我正在实例化ArticleRepo的实例(希望我做对了)。

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult New (Article article)
{
    try
    {
        if (ModelState.IsValid)
        {
            var userId = User.Identity.GetUserId();

            Article newArticle = new Article
            {
                Title = article.Title,
                Content = article.Content,
                AuthorId = userId,
                CreatedAt = DateTime.Now,
                LastUpdated = DateTime.Now
            };

            _ArticleRepo.InsertArticle(newArticle);
            _ArticleRepo.Save();

            return RedirectToAction("Details", "Article", new { id = article.Id });
        }
    } catch (DataException)
    {
        ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
    }

   return View(article);
}

Getting the error when I hit _ArticleRepo.InsertArticle(newArticle); 当我点击_ArticleRepo.InsertArticle(newArticle);时收到错误_ArticleRepo.InsertArticle(newArticle);

Remove the default constructor from your controller: 从控制器中删除默认构造函数:

public ArticleController(){}

and this will outline the issue. 这将概述问题。 The example you are following is using Dependency Injection which is a very good pattern to be learning. 您要遵循的示例使用了依赖注入,这是一个很好的学习模式。 Unfortunately, by default, MVC is expecting controllers not to have dependencies, though they have provided hooks to accommodate alternative controller factories. 不幸的是,默认情况下,MVC期望控制器具有依赖项,尽管它们提供了挂钩来容纳替代的控制器工厂。 Most IoC containers (Inversion of Control, which goes hand-in-hand with Dependency Injection) support MVC controller injection. 大多数IoC容器(控制反转,与依赖注入一起使用)都支持MVC控制器注入。

Have a look into the Autofac IoC container as it is quite a good take on the pattern and is easy to configure/use, plus it has pretty good documentation. 看一下Autofac IoC容器,因为它是该模式的一个很好的例子,并且易于配置/使用,并且它具有非常好的文档。

https://autofaccn.readthedocs.io/en/latest/integration/mvc.html https://autofaccn.readthedocs.io/en/latest/integration/mvc.html

Alternatively you can read up on Unity, Ninject, Castle Windsor, or a number of others, but these 4 are arguably the most common ones you will find in the wild. 另外,您可以阅读Unity,Ninject,Castle Windsor或其他一些书籍,但可以说这4种是在野外最常见的书籍。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 NullReferenceException:对象引用未设置为对象#2的实例 - NullReferenceException: Object reference not set to an instance of an object #2 错误:NullReferenceException:未将对象引用设置为对象的实例 - ERROR: NullReferenceException: Object reference not set to an instance of an object NullreferenceException - 对象引用未设置为对象的实例 - NullreferenceException - Object Reference is not set to an instance of a object 未处理NullReferenceException,未将对象引用设置为对象的实例 - NullReferenceException was unhandled, Object Reference not set to an instance of an object 对象引用未设置为对象存储库的实例 - object reference is not set to an instance of an object repository 空引用:对象引用未设置为对象的实例 - Null Reference : Object reference not set to an instance of an object 使用ASP.NET 5和MVC 6检查会话是否为空时,获取NullReferenceException和对象引用未设置为对象的实例 - Getting NullReferenceException and object reference not set to an instance of an object when checking if session is null with ASP.NET 5 and MVC 6 ManualResetEvent.WaitOne()抛出NullReferenceException:对象引用未设置为对象的实例 - ManualResetEvent.WaitOne() throws NullReferenceException: Object reference not set to an instance of an object 表单上的多个PartialViews产生NullReferenceException:对象引用未设置为对象的实例 - Multiple PartialViews On A Form Yielding NullReferenceException: Object reference not set to an instance of an object NullReferenceException:对象引用未设置为Chrome中的对象实例,但不是IE吗? - NullReferenceException: Object reference not set to an instance of an object In Chrome but not IE?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM