简体   繁体   中英

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.

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).

[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);

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. Most IoC containers (Inversion of Control, which goes hand-in-hand with Dependency Injection) support MVC controller injection.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM