【问题标题】:C# .net core - dependency injection reference to memorycacheC# .net core - 对内存缓存的依赖注入引用
【发布时间】: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&lt;IHttpService, HttpService&gt;();你首先需要创建IHttpService接口。然后,您可以将IHttpService 注入到您从中调用它的类的构造函数中
  • 你添加了https://www.nuget.org/packages/Microsoft.Extensions.Caching.Memory/ 包吗?

标签: c# .net-core dependency-injection dependencies


【解决方案1】:

我认为你有两种方法可以解决这个问题:

解决方案 A

将您的 HttpService 作为范围(每个请求的实例)注入,它将具有单个 TokenService 实例并且应该可以正常工作。

services.AddScoped<HttpService>();

解决方案 B

您可以通过构造函数创建 HttpService 的实例,但在这种情况下,您应该将 ITokenService 注入到创建 HttpService 的同一服务中,并将其作为参数传递。

public class SomeClass 
{
    private readonly ITokenService _tokenService;

    public SomeClass(ITokenService tokenService)
    {
        _tokenService = tokenService;
    }

    public HttpService CreateHttpService()
    {
        return new HttpService(_tokenService);
    }
}

我会选择第一个解决方案,但我会包含第二个解决方案,因为这可能有助于您理解问题

【讨论】:

    【解决方案2】:

    您的代码在每次调用代码时都会创建一个新的MemoryCache,这意味着正在创建一个新的缓存,因此当此代码第二次运行时,它将使用与第一次执行不同的空缓存。这就是缓存为空的原因。

    HttpService httpService = new HttpService(new TokenService(new MemoryCache(new MemoryCacheOptions())));
    

    在您配置依赖注入的地方,您应该添加以下行以将您的 HttpService 注册为新的依赖

    services.AddSingleton<IHttpService, HttpService>();
    

    *请注意,此行将要求您添加一个新的 IHttpService HttpService 实现。

    然后,无论您需要访问HttpService,您都应该注入新的IHttpService,并让依赖注入包含处理其他所有内容。

    例如:

    public class MyService
    {
        private readonly IHttpService _httpService { get; set; }
        public MyService(IHttpService httpService)
        {
            _httpService = httpService;
        }
    
        public void MyMethod()
        {
            var readers = _httpService.GetReadersFromExternalApi("Example Request");
        }
    }
    

    【讨论】:

    • 那行得通!这解决了问题 - 看起来我必须阅读一些关于依赖注入的内容......
    猜你喜欢
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2021-07-15
    • 2020-12-20
    相关资源
    最近更新 更多