Click here to Skip to main content
15,920,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Currently i'm trying to upgrade my old blog to .NET 7. While upgrading i thought, i can remove all hardcoded stuff, so everyone can use it.

I have the following Program.cs:

C#
public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.Configuration.AddJsonFile("appsettings.json");

        builder.Configuration.AddUserSecrets("845be935-7d32-419f-9734-f9458e0be851");

        builder.Services.Configure<AppSettings>(builder.Configuration);        

        builder.Services.AddTransient<SeedData>();

        SeedData.UserAsync();
        ....
    }


The SeedData is:

C#
public class SeedData
    {
        private static MannsContext? _ctx;
        private static UserManager<MannsUser>? _userMgr;
        private static ILogger<SeedData>? _logger;
        private static IConfiguration? _config;

        public SeedData(MannsContext ctx, UserManager<MannsUser> userMgr, ILogger<SeedData> logger, IConfiguration config)
        {
            _ctx = ctx;
            _userMgr = userMgr;
            _logger = logger;
            _config = config;
        }
        
        public static async Task UserAsync()
        {
            // Seed User
       (X)  string email = _config.GetValue<string>("Blog:Email");
            string username = _config.GetValue<string>("Blog:Username");
            string password = _config.GetValue<string>("Blog:Password");

            if (await userMgr.FindByNameAsync(username) == null)
            {
                var user = new MannsUser()
                {
                    Email = email,
                    UserName = username,
                    EmailConfirmed = true,
                };

                var result = await userMgr.CreateAsync(user, password);
                if (!result.Succeeded)
                {
                    throw new InvalidProgramException("Failed to create seed user");
                }
            }
        }
    }


After execution i running into the "System.NullReferenceException: "Object reference not set to an instance of an object."" on the marked line, while trying to get the email.

Currently i'm unsure, why this error happens. Maybe i missed anything?

What I have tried:

Read that one Code samples migrated to the new minimal hosting model in 6.0 | Microsoft Learn[^]
Posted
Updated 10-Dec-22 12:44pm
v2

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
Yeah, you missed something. Why is UserAsync (bad name by the way) static when it depends on the fields of the class being initialized before it's called? You never create an instance of the SeedData class, therefor the instance variables never get initialized, like _config.

Method names should be of the form "verb" or "verbnoun". Property names are usually "nouns".
 
Share this answer
 
v2
The error you're seeing is a NullReferenceException, which occurs when you try to access a member of an object that is null. In this case, it looks like the _config field in your SeedData class is null when the UserAsync method tries to access it.

One possible reason for this is that the SeedData class is static, so the _config field will also be static. That means it will be null unless you explicitly set it to an instance of IConfiguration before trying to use it.

You could try changing your SeedData class to be non-static, and then passing in the necessary dependencies (e.g. IConfiguration) when you create an instance of the class. This way, you can ensure that the _config field will be initialized with a valid instance before you try to use it.

Here's an example of how you could do that:

C#
public class SeedData
{
    private MannsContext? _ctx;
    private UserManager<MannsUser>? _userMgr;
    private ILogger<SeedData>? _logger;
    private IConfiguration? _config;

    public SeedData(MannsContext ctx, UserManager<MannsUser> userMgr, ILogger<SeedData> logger, IConfiguration config)
    {
        _ctx = ctx;
        _userMgr = userMgr;
        _logger = logger;
        _config = config;
    }

    public async Task UserAsync()
    {
        // Seed User
        string email = _config.GetValue<string>("Blog:Email");
        string username = _config.GetValue<string>("Blog:Username");
        string password = _config.GetValue<string>("Blog:Password");

        if (await userMgr.FindByNameAsync(username) == null)
        {
            var user = new MannsUser()
            {
                Email = email,
                UserName = username,
                EmailConfirmed = true,
            };

            var result = await userMgr.CreateAsync(user, password);
            if (!result.Succeeded)
            {
                throw new InvalidProgramException("Failed to create seed user");
            }
        }
    }
}


You would then need to update your Main method to create an instance of SeedData and call the UserAsync method on that instance, like this:

C#
public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);

    builder.Configuration.AddJsonFile("appsettings.json");

    builder.Configuration.AddUserSecrets("845be935-7d32-419f-9734-f9458e0be851");

    builder.Services.Configure<AppSettings>(builder.Configuration);        

    builder.Services.AddTransient<SeedData>();

    // Create an instance of SeedData and call UserAsync on it
    var seedData = new SeedData(...);
    seedData.UserAsync();
    ....
}


I hope this helps!
 
Share this answer
 
Comments
Sascha Manns 11-Dec-22 0:20am    
@MikeBrainy: Thank you very much. This one helped. I don't understand, why i made that class static, it doesn't make sense.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900