IMemoryCache 依赖注入外部控制器



我有一个带有API的 ASP.NET 核心MVC项目。

然后,我在名为基础结构的同一解决方案中有一个类库。

我的 API 在类UserRepository中调用类库基础结构内的存储库方法

。如果我在 API 控制器中使用:

private static IMemoryCache _memoryCache;
public Api(IMemoryCache cache) //Constructor
{
_memoryCache = cache;
}

我可以将缓存使用到控制器中。 但我希望 ASP.NET 注入要在基础结构库内的UserRepository类中使用的相同引用。

这样我就可以从 API 调用,例如

UserRepository.GetUser(Id);

在 UserRepository 类中:

namespace Infrastructure
{
public class UserRepository
{
public static User GetUser(Id)
{
**//I want to use the Cache Here**
}
}
}

即使不是控制器,如何告诉 ASP.NET 将IMemoryCache注入UserRepository类?

避免所有(静态单例、活动记录模式和静态类)一起使用的具体解决方案:

public class ApiController : Controller
{
private readonly UserRepository_userRepository;
public ApiController(UserRepository userRepository)
{
_userRepository = userRepository;
}
public Task<IActionResult> Get() 
{
// Just access your repository here and get the user
var user = _userRepository.GetUser(1);
return Ok(user);
}
}
namespace Infrastructure
{
public class UserRepository
{
public readonly IMemoryCache _memoryCache;
public UserRepository(IMemoryCache cache)
{
_memoryCache = cache;
}
public User GetUser(Id)
{
// use _memoryCache here
}
}
}
// Startup.cs#ConfigureServices
services.AddMemoryCache();

依赖注入和static不能很好地结合在一起。选择其中之一,否则您将不断遇到这样的困难。我建议您将UserRepository添加到依赖项注入容器中,将IMemoryCache添加到构造函数中,并在控制器中注入存储库。

关键是在应用程序的所有层中实现依赖项注入,而不仅仅是在 Web API 层中。

最新更新