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:
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()
{
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:
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>();
var seedData = new SeedData(...);
seedData.UserAsync();
....
}
I hope this helps!