0
votes

I want to remove duplicated singleton service for BuildServiceProvider method. I understand I should use the existing DI service but I can't access the GetService method. I am new to DI and I appreciate it if someone could say how to access the GetService method without getting new service. Code below. Thanks.

MESSAGE: Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.

public void ConfigureServices(IServiceCollection services){

services.AddAuthorization(options =>
      {
        var sp = services.BuildServiceProvider();//CODE ISSUE HERE
        var permissionService = sp.GetService<IPermissionService>();
        if (permissionService != null)
        {
          foreach (var permission in permissionService.GetPrivilegePermissions().Select(x => x.Name)
                   .Distinct())
          {

            options.AddPolicy(permission, policy => policy.Requirements.Add(new 
 PermissionRequirement(permission)));

          }

        }

      });

 

}
1

1 Answers

0
votes

You have written a lambda method to configure an object. However, since all Microsoft services follow the options pattern, you could instead write a service to configure it. Injecting any other service you want. You may implement any number of IConfigureOptions<T> services for any options type.

public class ConfigureAuthorization : IConfigureOptions<AuthorizationOptions>{
    public ConfigureAuthorization( ... ){}

    public void Configure(AuthorizationOptions options){
        // ...
    }
}

services.AddAuthorization();
services.AddSingleton<IConfigureOptions<AuthorizationOptions>, ConfigureAuthorization>();

Note, beware of any potential scoping issues.