【发布时间】:2021-11-20 11:34:33
【问题描述】:
为了在 MemoryCache(.net core 3.1 API)中存储 Oauth 令牌 - 我找到了下面的示例(省略了一些部分),但我找不到调用 HTTPservice 的构造函数的方法,因此它使用了 memorycache .
首先有一个接口定义:
public interface ITokenService
{
string FetchToken();
}
然后是接口实现
public class TokenService : ITokenService
{
private readonly IMemoryCache cache;
public TokenService(IMemoryCache cache)
{
this.cache = cache;
}
public string FetchToken()
{
string token = string.Empty;
if (!cache.TryGetValue("TOKEN", out token))
{
var tokenValue = this.GetTokenFromApi();
var options = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(
TimeSpan.FromSeconds(3600));
cache.Set("TOKEN", tokenValue, options);
token = tokenValue;
}
return token;
}
private string GetTokenFromApi()
{
return "Test";
}
}
然后在startup.cs中添加memorycache和TokenService
services.AddMemoryCache();
services.AddSingleton<ITokenService, TokenService>();
最后一个使用缓存中的令牌的 HTTP 服务是这样实现的:
public class HttpService
{
private ITokenService token;
public HttpService(ITokenService token)
{
this.token = token;
}
public string GetReadersFromExternalApi(string requestUrl)
{
return token.FetchToken();
}
}
此处描述的问题
要使用HTTPService,必须调用构造函数 - 但构造函数需要 TokenService 作为参数,TokenService 需要在构造函数中使用 IMemoryCache。
所以我尝试使用这行代码创建一个新的HTTPservice 对象,但缓存在连续调用时为空 - 那么应该将哪些参数传递给构造函数以引用 tokenservice/memorycache?
var httpService
= new HttpService(new TokenService(new MemoryCache(new MemoryCacheOptions())));
【问题讨论】:
-
你需要在你的依赖注入中注册你的HttpService:
services.AddSingleton<IHttpService, HttpService>();你首先需要创建IHttpService接口。然后,您可以将IHttpService注入到您从中调用它的类的构造函数中 -
你添加了
https://www.nuget.org/packages/Microsoft.Extensions.Caching.Memory/包吗?
标签: c# .net-core dependency-injection dependencies