简体   繁体   中英

.net core DI injection duplicated singleton service for BuildServiceProvide

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)));

          }

        }

      });

 

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM