-2

I have a controller class inside my ASP.NET server and I'm trying to get a list of all the data inside a table in my MySQL database. But for some reason my context variable inside my controller is null.

The error (on my context variable):

Object reference not set to an instance of an object

My controller class:

using Dyslexia.Managers;
using Dyslexia.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;

namespace Dyslexia.Controllers
{
    public class SchoolController : Controller
    {
        [HttpGet]
        [Route("Api/Schools")]
        public IEnumerable<SchoolModel> GetAllSchools()
        {
            SchoolManager context = HttpContext.RequestServices.GetService(typeof(SchoolManager)) as SchoolManager;
            return context.GetAllSchools().ToArray();
        }
    }
}

My SchoolManager class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dyslexia.Models;
using Microsoft.AspNetCore.Mvc;
using MvcSakilaCore.Models;
using MySql.Data.MySqlClient;

namespace Dyslexia.Managers
{
    public class SchoolManager
    {
        public string ConnectionString { get; set; }

        public SchoolManager(string connectionString)
        {
            ConnectionString = connectionString;
        }

        private MySqlConnection GetConnection()
        {
            return new MySqlConnection(ConnectionString);
        }

        public List<SchoolModel> GetAllSchools()
        {
            List<SchoolModel> schoolsList = new List<SchoolModel>();

            using (MySqlConnection dbConnection = GetConnection())
            {
                dbConnection.Open();
                MySqlCommand cmd = new MySqlCommand("SELECT * FROM schools", dbConnection);

                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        schoolsList.Add(new SchoolModel()
                        {
                            Id = reader.GetInt32("Id"),
                            Name = reader.GetString("Name"),
                            Address = reader.GetString("Address"),
                            City = reader.GetString("City"),
                            PhoneNumber = reader.GetString("PhoneNumber"),
                            State = reader.GetString("State"),
                            Country = reader.GetString("Country"),
                            Zip = reader.GetString("Zip"),
                            AdminId = reader.GetInt32("AdminId"),
                            Active = reader.GetInt32("Active"),
                        });
                    }
                }
            }

            return schoolsList;
        }
    }
}
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
GSepetadelis
  • 417
  • 3
  • 11
  • Did you actually register SchoolManager with the DI container? You know you're using the "service locator" pattern? Generally something you should avoid. – mason May 22 '22 at 17:32
  • @JohnG No, it doesn't answer my question – GSepetadelis May 22 '22 at 17:33
  • @mason I have the same code in my other controllers (with other managers of course) and it works – GSepetadelis May 22 '22 at 17:35
  • You didn't actually answer my question. Please re-read and respond to specifically what was asked. – mason May 22 '22 at 17:37
  • @mason I don't know what did you mean when you say if i have registered my class, i'm beginner on .net :( – GSepetadelis May 22 '22 at 17:44
  • Do you understand what a NullReferenceException is? You're attempting to invoke a method or access a member of an object that is null. So, you must figure out *why* the object is null. You're obtaining it via `HttpContext.RequestServices.GetService(typeof(SchoolManager))`. Did you research how HttpContext.RequestServices.GetService works? You must have included it in your code for a reason. So, why did you write that line of code? How do you expect it to know where to go to obtain an instance of SchoolManager? – mason May 22 '22 at 17:47
  • @GSepetadelis - That's okay. We are all learning. However mason brought up a good point. The problem is that `HttpContext.RequestServices.GetService(typeof(SchoolManager)) as SchoolManager` is returning `null` (you would know that if you set a breakpoint on it to inspect the value). However, since your service locator registration code is elsewhere and you didn't post it, this question is not answerable. – NightOwl888 May 22 '22 at 17:49
  • @mason Yes, i understand what a NullReferenceException is but i can't figure out why is my variable null – GSepetadelis May 22 '22 at 17:50
  • 2
    @GSepetadelis Yes, you stated that in your question. I asked you several other questions in my last comment. Please re-read and respond to them. Make sure you're fully reading the comments and understanding what's being asked for you, as that will reduce the amount of back and forth and we can get this straightened out with less fuss. – mason May 22 '22 at 17:52
  • @NightOwl888 I have post the code from both controller and the manager class, i don't have any other class to share here i think – GSepetadelis May 22 '22 at 18:09
  • 3
    But you should have. As the services need to be registered somewhere. If you don't do that, you should possible read about it [here](https://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection). Stop developing your app and make sure you understand the fundamentals of what you are trying to use. – Exitare May 22 '22 at 18:18

0 Answers0