I want to create a caching service that receives a regular service as a constructor parameter. Then, when the cache key does not exist, I want to call the regular maintenance and update cache. My idea is to have the same interface in a regular service and cache. But when I try to implement the implementation of the caching service and execute the method, I get an exception:
The registered delegate for type IUserRepository made an exception. The configuration is invalid. The type CacheUserRepository directly or indirectly depends on itself.
My code is:
public interface IUserRepository { UserDTO Get(int userId); } public class UserRepository : IUserRepository { public virtual UserDTO Get(int userId) { return new UserDTO() { Id = 1, Age = 28, Name = "Emil" }; } }
Here is my cache repository:
public class CacheUserRepository : IUserRepository { private readonly IUserRepository _userRepository; private readonly ICache _cache; public CacheUserRepository(IUserRepository userRepository, ICache cache) { _userRepository = userRepository; _cache = cache; } public DTO.UserDTO Get(int userId) { var userKey = "User_" + userId.ToString(); UserDTO val = _cache.Get<UserDTO>(userKey); if (val != null) return val; UserDTO user = _userRepository.Get(userId); _cache.Add(userKey, user); return user; } }
Here is my root of the composition:
public class ExecutionClass { private readonly Container _container; public ExecutionClass() { _container = new Container(); _container.Register<IUserRepository, CacheUserRepository>(); _container.Register<ICache, Cache>(); } public UserDTO GetUser(int Id) {
source share