How to call interface's method at runtime using program.cs (.NET 6 preview 7)

Khanh Duy Van Ba 26 Reputation points
2021-09-05T07:32:40.507+00:00

Hi, I'm trying to call method in interface class in program.cs but it seem to be ignored.
void Init(IDefaultAccountInit init)
{
init.Initialize();
}

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,307 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,520 questions
0 comments No comments
{count} vote

Accepted answer
  1. Zhi Lv - MSFT 32,056 Reputation points Microsoft Vendor
    2021-09-07T07:30:34.89+00:00

    Hi @Khanh Duy Van Ba ,

    From your code and description, I assume you want to call the method in the interface class to seed data for the Identity table, right? If that is the case, you can refer the following sample:

    Interface and the Initialize method:

    public interface IDataRepository  
    {  
        public void Initialize(ApplicationDbContext db, UserManager<IdentityUser> userManager);  
    }  
    
    public class DataRepository : IDataRepository  
    {  
          
        public void Initialize(ApplicationDbContext db, UserManager<IdentityUser> _userManager)  
        {  
            var user = _userManager.Users.ToList();  
            //you can seed the Identity User table from here.  
        }  
    }  
    

    Register the service in the ConfigureServices method: (I didn't configure the Role Manager, you can set it in your application)

        services.AddDbContext<ApplicationDbContext>(options =>  
            options.UseSqlServer(  
                Configuration.GetConnectionString("DefaultConnection")));  
        services.AddDatabaseDeveloperPageExceptionFilter();  
    
        services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)  
            .AddEntityFrameworkStores<ApplicationDbContext>();  
    
        services.AddScoped<IDataRepository, DataRepository>();  
    

    Then, in the program.cs file, use the GetRequiredService() method to get the relate service:

        public static void Main(string[] args)  
        {  
            var host = CreateHostBuilder(args).Build();  
    
            //required using Microsoft.Extensions.DependencyInjection;  
            // required using Microsoft.AspNetCore.Identity;  
            using (var scope = host.Services.CreateScope())  
            {  
                var services = scope.ServiceProvider;  
                try  
                {  
                    var dbcontext = services.GetRequiredService<ApplicationDbContext>();  
                    var userManager = services.GetRequiredService<UserManager<IdentityUser>>();  
                    var repository = services.GetRequiredService<IDataRepository>();  
    
                    repository.Initialize(dbcontext, userManager);  
                }  
                catch (Exception ex)  
                {  
                    var logger = services.GetRequiredService<ILogger<Program>>();  
                    logger.LogError(ex, "An error occurred while seeding the database.");  
                }  
            }   
            host.Run();  
        }  
    

    The result as below:

    129700-58.gif

    Besides, you can also refer the following article to initialize data into database:

    Initialize DB with test data


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. P a u l 10,411 Reputation points
    2021-09-05T12:23:46.243+00:00

    I see - what should be calling your Init method?

    1 person found this answer helpful.

  2. P a u l 10,411 Reputation points
    2021-09-05T12:19:33.127+00:00

    When you say ignored do you mean that your Init method is called, but init.Initialize isn't?