IMemoryCache依赖注入外部控制器

Fra*_*llo 7 c# asp.net-core-mvc asp.net-core

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

然后我在名为Infrastructure的同一解决方案中有一个类库.

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

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

private static IMemoryCache _memoryCache;
public Api(IMemoryCache cache) //Constructor
{
    _memoryCache = cache;
}
Run Code Online (Sandbox Code Playgroud)

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

这样我就可以从API中调用一个类似的方法

UserRepository.GetUser(Id);
Run Code Online (Sandbox Code Playgroud)

并在UserRepository类中:

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

我怎么能告诉ASP.NET注入IMemoryCacheUserRepository类,即使不是一个控制器?

Tse*_*eng 11

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

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();
Run Code Online (Sandbox Code Playgroud)

  • 当然,你需要在启动时注册它,`services.AddScoped&lt;UserRepository&gt;()` 或 `services.AddScoped&lt;IUserRepository,UserRepository&gt;()`,这取决于你是否将它拆分成一个接口。您可以并且应该将其拆分为一个接口,这提高了代码的可测试性,尽管您也可以注入具体的类,但是您将失去在单元测试中轻松模拟它的能力 (2认同)

Hen*_*ema 5

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

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