Search code examples
c#ninjectstrategy-pattern

How to use strategy pattern with Ninject


I have two repositories AlbumRepository with interface IAlbumRepository and CachedAlbumRepository with interface IAlbumRepository which has constructor interface IAlbumRepository. I need inject with Ninject ICachedAlbumRepository with CachedAlbumRepository and constructor with AlbumRepository.

How to achieve it with Ninject?

Same approach with structure map

x.For<IAlbumRepository>().Use<CachedAlbumRepository>()

.Ctor<IAlbumRepository>().Is<EfAlbumRepository>();

    public class CachedAlbumRepository : IAlbumRepository
    {
        private readonly IAlbumRepository _albumRepository;

        public CachedAlbumRepository(IAlbumRepository albumRepository)
        {
            _albumRepository = albumRepository;
        }

        private static readonly object CacheLockObject = new object();

        public IEnumerable<Album> GetTopSellingAlbums(int count)
        {
            string cacheKey = "TopSellingAlbums-" + count;

            var result = HttpRuntime.Cache[cacheKey] as List<Album>;

            if (result == null)
            {
                lock (CacheLockObject)
                {
                    result = HttpRuntime.Cache[cacheKey] as List<Album>;

                    if (result == null)
                    {
                        result = _albumRepository.GetTopSellingAlbums(count).ToList();

                        HttpRuntime.Cache.Insert(cacheKey, result, null, 

                            DateTime.Now.AddSeconds(60), TimeSpan.Zero);
                    }
                }
            }

            return result;
        }
    }

Solution

  • You need to create 2 bindings - one that says inject CachedAlbumRepository into anything that needs an IAlbumRepository and another that says inject a normal AlbumRepository into CachedAlbumRepository. These bindings should do that:

    Bind<IAlbumRepository>()
        .To<CachedAlbumRepository>();
    
    Bind<IAlbumRepository>()
        .To<AlbumRepository>()
        .WhenInjectedInto<CachedAlbumRepository>();