Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IMemoryCache Dependency Injection outside controllers

I have an ASP.NET Core MVC Project with an API.

I then have a Class Library in the same solution named Infrastructure.

My API calls a repository method inside the Class Library Infrastructure, in the class UserRepository

If I use in the API Controller:

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

I can use the cache into the controller. But I want ASP.NET to inject the same reference to be used in the UserRepository class inside the Infrastructure Library.

This way I can call from the API, a method like

UserRepository.GetUser(Id);

and in the UserRepository Class:

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

How can I tell ASP.NET to inject the IMemoryCache into the UserRepository class even if is not a controller?

like image 246
Francesco Cristallo Avatar asked Dec 03 '16 10:12

Francesco Cristallo


1 Answers

The concrete solution to avoid all (static singletons, active record pattern and static classes) together:

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();
like image 75
Tseng Avatar answered Oct 04 '22 03:10

Tseng