0

i am using the following code in configureservices in startup.cs in netcore 3

Can someone show how i can do this a better way, how do i inject it into configure method? I need to access the database before dependency injection has resolved it but buildservices isnt recommended.

     public void ConfigureServices(IServiceCollection services)
        {

  services.AddDbContext<bookingsstrathContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyEntities2")));

        services.AddScoped<IMyAccountService, MyAccountService>();

var sp = services.BuildServiceProvider();
    
            // Resolve the services from the service provider
            var _myAccountService = sp.GetService<IMyAccountService>();
    
    
            //get the local role from the local database
            if (_myAccountService.IsUserInRole(context.Principal.GetUserGraphSamAccountName(), "Administrator"))
            {
                //myIdentity.AddClaim(new Claim(ClaimTypes.Role, "Administrator"));
                context.Principal.AddUserSystemRole("Administrator");
    
            }
    }
user900566
  • 93
  • 1
  • 9
  • Please check this answer using custom configuration provider https://stackoverflow.com/a/73838748/6453193. Hope this is you are looking for :) – Mary Sep 24 '22 at 16:22

1 Answers1

0

You can add your account service in program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices(serviceCollection =>
                     serviceCollection.AddScoped<IMyAccountService, MyAccountService>())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

and then you can use it in startup.cs

 private readonly IMyAccountService _myAccountService;
        public Startup(IConfiguration configuration, IMyAccountService AccountService)
        {
            Configuration = configuration;
            _myAccountService = AccountService
        }
NAS
  • 311
  • 2
  • 6
  • Doesnt work unfortunately, is it because it depends on the dbcontext being configured in program.cs as well? – user900566 Mar 17 '21 at 17:44