C
C#17mo ago
ツ᲼

❔ 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);
}
}
);
1 Reply
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server