title: Authorization Policy using Dependency Injection in asp.net core
body: <p>I want to create policy based authorisation for aspnet.core</p>
  
  <p>I have lots of policies that I want to implement and I don't want to bloat the startup.cs file with policies.</p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
  {
      services.AddAuthorization(options =&gt;
      {
          options
              .AddPolicy("Policy1", policyBuilder =&gt;
              {
                  policyBuilder
                      .RequireClaim("scope", "1")
                      .Build();
              }).AddPolicy("Policy2", policyBuilder =&gt;
              {
                  policyBuilder
                      .RequireClaim("scope", "2")
                      .Build();
              }).AddPolicy("Policy3", policyBuilder =&gt;
              {
                  policyBuilder
                      .RequireClaim("scope", "3")
                      .Build();
              }).AddPolicy("Policy4", policyBuilder =&gt;
              {
                  policyBuilder
                      .RequireClaim("scope", "4")
                      .Build();
                  ;
              });
      });
  }
  </code></pre>
  
  <p>I want to inject all the policies at startup.</p>
  
  <p>Does anyone have any idea how to do this?</p>
  
  <p>I thought about creating a factory that gets all the policies by reflection, but I really want to be able to inject classes into the policies.</p>
  
  <p>e.g. </p>
  
  <pre><code>public interface IPolicy
  {
      string Name { get; }
      AuthorizationPolicy AuthorizationPolicy { get; }
  }
  
  public class UserCreatePolicy : IPolicy
  {
      public const string Name = "UserCreatePolicy";
  
      public UserCreatePolicy(IUserRoleService userRoleService)
      {
          _userRoleService = userRoleService;
      }
  
      public AuthorizationPolicy AuthorizationPolicy =&gt;
          new AuthorizationPolicyBuilder()
              .RequireClaim("scope", _userRoleService.GetRole(1))
              .Build();
  }
  
  public class AuthorizationPolicyFactory
  {
      public static void Create(AuthorizationOptions authorizationOptions)
      {
          typeof(IPolicy).Assembly
              .GetTypes()
              .Where(x =&gt; typeof(IPolicy).IsAssignableFrom(x) &amp;&amp; !x.IsAbstract &amp;&amp; !x.IsInterface)
              .ToList()
              .ForEach(type =&gt;
              {
                  if (Activator.CreateInstance(type) is IPolicy policy)
                  {
                      authorizationOptions.AddPolicy(policy.Name, policy.AuthorizationPolicy);
                  }
              });
      }
  }
  </code></pre>
  
  <p>Ideally I don't want to have to use reflection and instead use Dependency injection.</p>