How do I use the Decorator Pattern with Unity without explicitly specifying every parameter in the InjectionConstructor

This helpful article from David Haydn (EDIT: scam link removed, it could have been this article) shows how you can use the InjectionConstructor class to help you set up a chain using the decorator pattern with Unity. However, if the items in your decorator chain have other parameters in their constructor, the InjectionConstructor must explicitly declare each one of them (or Unity will complain that it can't find the right constructor). This means that you can't simply add new constructor parameters to items in the decorator chain without also updating your Unity configuration code.

Here's some example code to explain what I mean. The ProductRepository class is wrapped first by CachingProductRepository and then by LoggingProductRepostiory. Both CachingProductRepository and LoggingProductRepository, in addition to taking a IProductRepository in their constructor, also need other interfaces from the container.

    public class Product 
    {
        public int Id;
        public string Name;
    }

    public interface IDatabaseConnection { }

    public interface ICacheProvider 
    { 
        object GetFromCache(string key);
        void AddToCache(string key, object value);
    }

    public interface ILogger
    {
        void Log(string message, params object[] args);
    }


    public interface IProductRepository
    {
        Product GetById(int id);    
    }

    class ProductRepository : IProductRepository
    {
        public ProductRepository(IDatabaseConnection db)
        {
        }

        public Product GetById(int id)
        {
            return new Product() { Id = id, Name = "Foo " + id.ToString() };
        }
    }

    class CachingProductRepository : IProductRepository
    {
        IProductRepository repository;
        ICacheProvider cacheProvider;
        public CachingProductRepository(IProductRepository repository, ICacheProvider cp)
        {
            this.repository = repository;
            this.cacheProvider = cp;
        }

        public Product GetById(int id)
        {       
            string key = "Product " + id.ToString();
            Product p = (Product)cacheProvider.GetFromCache(key);
            if (p == null)
            {
                p = repository.GetById(id);
                cacheProvider.AddToCache(key, p);
            }
            return p;
        }
    }

    class LoggingProductRepository : IProductRepository
    {
        private IProductRepository repository;
        private ILogger logger;

        public LoggingProductRepository(IProductRepository repository, ILogger logger)
        {
            this.repository = repository;
            this.logger = logger;
        }

        public Product GetById(int id)
        {
            logger.Log("Requesting product {0}", id);
            return repository.GetById(id);
        }
    }

Here's a (passing) unit test. See the comments for the bits of surplus configuration I want to remove the need for:

    [Test]
    public void ResolveWithDecorators()
    {
        UnityContainer c = new UnityContainer();            
        c.RegisterInstance(new Mock().Object);
        c.RegisterInstance(new Mock().Object);
        c.RegisterInstance(new Mock().Object);

        c.RegisterType("ProductRepository");

        // don't want to have to update this line every time the CachingProductRepository constructor gets another parameter
        var dependOnProductRepository = new InjectionConstructor(new ResolvedParameter("ProductRepository"), new ResolvedParameter());
        c.RegisterType("CachingProductRepository", dependOnProductRepository);

        // don't want to have to update this line every time the LoggingProductRepository constructor changes
        var dependOnCachingProductRepository = new InjectionConstructor(new ResolvedParameter("CachingProductRepository"), new ResolvedParameter());
        c.RegisterType(dependOnCachingProductRepository);
        Assert.IsInstanceOf(c.Resolve());
    }

36
задан BenCr 4 April 2016 в 15:50
поделиться