/// <summary>
        /// Checks if the policies are satisfied for the given action.
        /// </summary>
        /// <param name="context">The policies checking context.</param>
        /// <returns>The policies checking result.</returns>
        public async Task <IPolicyResult <TAction> > CheckPoliciesAsync(TPolicyContext context)
        {
            if (this.logger == null)
            {
                // Getting the logger lazilly at the first call.
                this.logger = this.serviceProvider.GetService <ILogger <AuthorizedSpecificActionChecker <TPolicyContext, TAction, TSpecificAction> > >();
            }

            this.logger.LogDebug($"Checking the policies of the {this.SpecificActionType.FullName} specific action.");

            if (this.policies == null)
            {
                // Getting the policies lazilly at the first call.
                this.policies = PolicyCollection.Build(policyTypes, serviceProvider);
            }

            // Returning the specific action if it satisfies all the policies.
            bool result = await this.policies.CheckAsync(context).ConfigureAwait(false);

            if (result)
            {
                this.logger.LogDebug($"All the policies are satisfied. The {this.SpecificActionType.FullName} specific action execution is allowed.");
                return(new AllowedResult <TAction>(this.serviceProvider.GetRequiredService <TSpecificAction>()));
            }

            return(NotAllowedResult <TAction> .Default);
        }
コード例 #2
0
        /// <summary>
        /// Build a policy collection from the policy types using the given service provider.
        /// </summary>
        /// <param name="policyTypes">The types of the policies to satisfy.</param>
        /// <param name="serviceProvider">The service provider.</param>
        /// <returns></returns>
        public static PolicyCollection Build(HashSet <Type> policyTypes, IServiceProvider serviceProvider)
        {
            PolicyCollection policies = new PolicyCollection(serviceProvider);

            foreach (Type policyType in policyTypes)
            {
                policies.Add(serviceProvider.GetRequiredService(policyType) as IPolicy);
            }

            return(policies);
        }