ツ᲼
ツ᲼
CC#
Created by ツ᲼ on 7/26/2023 in #help
❔ Injecting rate limiter instance into other services in ASP.NET 7
Hey, does anyone know if it's possible to inject the rate limiter instance into other services in my WebApplication. I have registered my TokenBucketLimiter in my program.cs file and would like to access the instance in another service so i could see how many tokens are left and replenish them.
builder.Services.AddRateLimiter(options => options
.AddTokenBucketLimiter(policyName: "MyTokenBucketLimiter", options =>
{
options.TokensPerPeriod = 10;
options.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
options.QueueLimit = 10;
})
.OnRejected = async (context, token) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
context.HttpContext.Response.Headers.Add(HeaderNames.RetryAfter, ((int) retryAfter.TotalSeconds)
.ToString(NumberFormatInfo.InvariantInfo));
await context.HttpContext.Response.WriteAsync("Too many requests. Please try later again... ", token);
}
}
);
builder.Services.AddRateLimiter(options => options
.AddTokenBucketLimiter(policyName: "MyTokenBucketLimiter", options =>
{
options.TokensPerPeriod = 10;
options.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
options.QueueLimit = 10;
})
.OnRejected = async (context, token) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
context.HttpContext.Response.Headers.Add(HeaderNames.RetryAfter, ((int) retryAfter.TotalSeconds)
.ToString(NumberFormatInfo.InvariantInfo));
await context.HttpContext.Response.WriteAsync("Too many requests. Please try later again... ", token);
}
}
);
2 replies