【问题标题】:How do I use the Decorator Pattern with Unity without explicitly specifying every parameter in the InjectionConstructor如何在不明确指定 InjectionConstructor 中的每个参数的情况下将装饰器模式与 Unity 一起使用
【发布时间】:2011-08-31 20:46:42
【问题描述】:

David Haydn 的这篇有用的文章(编辑:已删除诈骗链接,可能是 this article)展示了如何使用 InjectionConstructor 类来帮助您使用 Unity 的装饰器模式设置链。但是,如果装饰器链中的项目在其构造函数中有其他参数,InjectionConstructor 必须显式声明它们中的每一个(否则 Unity 会抱怨它找不到正确的构造函数)。这意味着您不能简单地将新的构造函数参数添加到装饰器链中的项目而不更新您的 Unity 配置代码。

这里有一些示例代码来解释我的意思。 ProductRepository 类首先由CachingProductRepository 包装,然后由LoggingProductRepostiory 包装。 CachingProductRepository 和 LoggingProductRepository 除了在其构造函数中获取一个 IProductRepository 外,还需要来自容器的其他接口。

    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);
        }
    }

这是一个(通过)单元测试。请参阅 cmets 了解我想消除的多余配置:

    [Test]
    public void ResolveWithDecorators()
    {
        UnityContainer c = new UnityContainer();            
        c.RegisterInstance<IDatabaseConnection>(new Mock<IDatabaseConnection>().Object);
        c.RegisterInstance<ILogger>(new Mock<ILogger>().Object);
        c.RegisterInstance<ICacheProvider>(new Mock<ICacheProvider>().Object);

        c.RegisterType<IProductRepository, ProductRepository>("ProductRepository");

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

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

【问题讨论】:

  • 好吧,我以前从未使用过 unity,也许这已经过时了,但你不能用 injectionfactory 代替 injectionconstructor 吗?
  • @DarkSquirrel42 一个有趣的建议。不过,Action 可能必须调用具体的构造函数,这意味着只要构造函数发生更改,仍需要调用 Unity 配置代码。不过,它至少会导致编译错误,提醒您需要更改。
  • @DarkSquirrel42,再想一想,如果你只使用一个 InjectionFactory 其 Func 构建整个链,使用容器来实现其他依赖项,虽然你仍然没有与构造函数参数更改隔离,但在至少比我的原始代码更容易混淆,并且只需要在容器中注册一次。
  • 文章链接已损坏
  • 那个“有用的文章”现在是一个骗局网站,可能需要修复它。

标签: c# unity-container decorator


【解决方案1】:

感谢@DarkSquirrel42 的建议,另一种方法是使用InjectionFactory。缺点是每次将新的构造函数参数添加到链中的某些内容时,代码仍然需要更新。优点是代码更容易理解,并且只需一次注册到容器中。

Func<IUnityContainer,object> createChain = container =>
    new LoggingProductRepository(
        new CachingProductRepository(
            container.Resolve<ProductRepository>(), 
            container.Resolve<ICacheProvider>()), 
        container.Resolve<ILogger>());

c.RegisterType<IProductRepository>(new InjectionFactory(createChain));
Assert.IsInstanceOf<LoggingProductRepository>(c.Resolve<IProductRepository>());

【讨论】:

  • 这还有一个好处是对构造函数的改变会产生编译时间而不是运行时错误。
【解决方案2】:

请参阅this article,了解如何实现装饰器容器扩展。如果您的构造函数签名发生更改,这应该可以让您到达您想要的位置,而无需修改您的配置。

【讨论】:

  • 这是我最喜欢的解决方案!
【解决方案3】:

另一种解决方案是在代码库中添加类型参数,以帮助 Unity 解析您的修饰类型。幸运的是,Unity 完全能够自行解析类型参数及其依赖关系,因此我们在定义装饰器链时不必关心构造函数参数。

注册如下所示:

unityContainer.RegisterType<IService, Logged<Profiled<Service>>>();

这是一个基本的示例实现。注意模板化装饰器Logged&lt;TService&gt; 和Profiled&lt;TService&gt;。看看下面我到目前为止注意到的一些缺点。

public interface IService { void Do(); }

public class Service : IService { public void Do() { } }

public class Logged<TService> : IService where TService : IService
{
    private TService decoratee;
    private ILogger logger;

    public Logged(ILogger logger, TService decoratee) {
        this.decoratee = decoratee;
        this.logger = logger;
    }

    public void Do() {
        logger.Debug("Do()");
        decoratee.Do();
    }
}

public class Profiled<TService> : IService where TService : IService
{
    private TService decoratee;
    private IProfiler profiler;

    public Profiled(IProfiler profiler, TService decoratee) {
        this.decoratee = decoratee;
        this.profiler = profiler;
    }

    public void Do() {
        profiler.Start();
        decoratee.Do();
        profiler.Stop();
    }
}

缺点

  • 像uC.RegisterType&lt;IService, Logged&lt;IService&gt;&gt;(); 这样的错误注册将导致无限递归,导致应用程序堆栈溢出。这可能是插件架构中的漏洞。
  • 它在某种程度上使您的代码库变得丑陋。如果您放弃 Unity 并切换到不同的 DI 框架,那么这些模板参数对任何人都将毫无意义。

【讨论】:

    【解决方案4】:

    我为此敲了一个相当粗略的扩展方法,当我运行它时,它的行为符合预期:

    public static class UnityExtensions
    {
        public static IUnityContainer Decorate<TInterface, TDecorator>(this IUnityContainer container, params InjectionMember[] injectionMembers)
            where TDecorator : class, TInterface
        {
            return Decorate<TInterface, TDecorator>(container, null, injectionMembers);
        }
    
        public static IUnityContainer Decorate<TInterface, TDecorator>(this IUnityContainer container, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
            where TDecorator : class, TInterface
        {
            string uniqueId = Guid.NewGuid().ToString();
            var existingRegistration = container.Registrations.LastOrDefault(r => r.RegisteredType == typeof(TInterface));
            if(existingRegistration == null)
            {
                throw new ArgumentException("No existing registration found for the type " + typeof(TInterface));
            }
            var existing = existingRegistration.MappedToType;
    
            //1. Create a wrapper. This is the actual resolution that will be used
            if (lifetimeManager != null)
            {
                container.RegisterType<TInterface, TDecorator>(uniqueId, lifetimeManager, injectionMembers);
            }
            else
            {
                container.RegisterType<TInterface, TDecorator>(uniqueId, injectionMembers);
            }
    
            //2. Unity comes here to resolve TInterface
            container.RegisterType<TInterface, TDecorator>(new InjectionFactory((c, t, sName) =>
            {
                //3. We get the decorated class instance TBase
                var baseObj = container.Resolve(existing);
    
                //4. We reference the wrapper TDecorator injecting TBase as TInterface to prevent stack overflow
                return c.Resolve<TDecorator>(uniqueId, new DependencyOverride<TInterface>(baseObj));
            }));
    
            return container;
        }
    }
    

    在您的设置中:

    container.RegisterType<IProductRepository, ProductRepository>();
    
    // Wrap ProductRepository with CachingProductRepository,
    // injecting ProductRepository into CachingProductRepository for
    // IProductRepository
    container.Decorate<IProductRepository, CachingProductRepository>();
    
    // Wrap CachingProductRepository with LoggingProductRepository,
    // injecting CachingProductRepository into LoggingProductRepository for
    // IProductRepository
    container.Decorate<IProductRepository, LoggingProductRepository>();
    

    【讨论】:

    • 您能解释一下这是如何处理递归的吗?我无法理解 container.Registrations.First(r => r.RegisteredType == typeof(TInterface)).Mapped to type...
    • 您引用的行将查看现有注册,获取接口的现有注册(要装饰的具体 - existing)并记录该具体类型;然后注册装饰器,替换existing。在解决问题时,装饰器将使用该具体类型 (existing) 并将其注入装饰器,但您界面的所有其他用途都将使用装饰器。这样,如果需要,可以多次装饰。如果您使用命名注册,可能需要对其进行调整。
    • 我明白这一点,但无法理解为什么您总是首先从注册列表中检索。如果您有多个具有相同接口的注册类型,该怎么办?
    • 为一个接口拥有两种注册类型的唯一方法是,如果您使用命名注册来区分两者(因此 First() - 它假设它只会得到一个它 - 也许 Single会更好,idk ...),否则您会在那里发生冲突(Unity如何知道在给定情况下使用哪个?)。如果您使用命名注册,则需要修改此代码。
    • 这很好!我肯定+1,但我有点想知道你为什么说它“粗鲁”?代码看起来不错,并且完全符合它的要求。关于我要更改/添加的唯一一件事是在查找 existing 类型时进行检查 - 如果它尚未注册但使用适当的消息抛出异常......并且在查找类型时确保它尚未注册名称(尽管这值得商榷)。
    【解决方案5】:

    Mark Seeman 在另一个stackoverflow post 中提到了最简洁 效果很好 的答案。它简洁,不要求我使用命名注册或建议我使用 Unity 扩展。考虑一个名为 ILogger 的接口,它有两个实现,即 Log4NetLogger 和一个名为 DecoratorLogger 的装饰器实现。您可以将 DecoratorLogger 注册到 ILogger 接口,如下所示:

    container.RegisterType<ILogger, DecoratorLogger>(
        new InjectionConstructor(
            new ResolvedParameter<Log4NetLogger>()));
    

    【讨论】:

      【解决方案6】:

      当我在等待这个问题的答案时,我想出了一个相当老套的解决方法。我在IUnityContainer 上创建了一个扩展方法,它允许我使用反射注册装饰器链来创建 InjectionConstructor 参数:

      static class DecoratorUnityExtensions
      {
          public static void RegisterDecoratorChain<T>(this IUnityContainer container, Type[] decoratorChain)
          {
              Type parent = null;
              string parentName = null;
              foreach (Type t in decoratorChain)
              {
                  string namedInstance = Guid.NewGuid().ToString();
                  if (parent == null)
                  {
                      // top level, just do an ordinary register type                    
                      container.RegisterType(typeof(T), t, namedInstance);
                  }
                  else
                  {
                      // could be cleverer here. Just take first constructor
                      var constructor = t.GetConstructors()[0];
                      var resolvedParameters = new List<ResolvedParameter>();
                      foreach (var constructorParam in constructor.GetParameters())
                      {
                          if (constructorParam.ParameterType == typeof(T))
                          {
                              resolvedParameters.Add(new ResolvedParameter<T>(parentName));
                          }
                          else
                          {
                              resolvedParameters.Add(new ResolvedParameter(constructorParam.ParameterType));
                          }
                      }
                      if (t == decoratorChain.Last())
                      {
                          // not a named instance
                          container.RegisterType(typeof(T), t, new InjectionConstructor(resolvedParameters.ToArray()));
                      }
                      else
                      {
                          container.RegisterType(typeof(T), t, namedInstance, new InjectionConstructor(resolvedParameters.ToArray()));
                      }
                  }
                  parent = t;
                  parentName = namedInstance;
              }
          }
      }
      

      这让我可以使用更易读的语法来配置我的容器:

      [Test]
      public void ResolveWithDecorators2()
      {
          UnityContainer c = new UnityContainer();
          c.RegisterInstance<IDatabaseConnection>(new Mock<IDatabaseConnection>().Object);
          c.RegisterInstance<ILogger>(new Mock<ILogger>().Object);
          c.RegisterInstance<ICacheProvider>(new Mock<ICacheProvider>().Object);
      
          c.RegisterDecoratorChain<IProductRepository>(new Type[] { typeof(ProductRepository), typeof(CachingProductRepository), typeof(LoggingProductRepository) });
      
          Assert.IsInstanceOf<LoggingProductRepository>(c.Resolve<IProductRepository>());
      
      }
      

      我仍然很想知道 Unity 是否有更优雅的解决方案

      【讨论】:

        【解决方案7】:

        我知道这篇文章有点过时了,但实际上最新版本没有功能齐全的 Unity 装饰器实现(有很多重大更改,请参阅Unity wiki)。

        我接受了 @garryp answer(在我看来,这是这里唯一正确的答案)并根据最新的 Unity 容器 API 更改对其进行了修改:

        public static IContainerRegistry RegisterDecorator<TInterface, TDecorator>(this IContainerRegistry container, ITypeLifetimeManager lifetimeManager, Type[] additionalInterfaces, params InjectionMember[] injectionMembers)
            where TDecorator : class, TInterface
        {    
            var unityContainer = container.GetContainer();
        
            var existingRegistration = unityContainer.Registrations.LastOrDefault(r => r.RegisteredType == typeof(TInterface));
        
            if (existingRegistration == null)
            {
                throw new ArgumentException("No existing registration found for the type " + typeof(TInterface));
            }
        
            var existing = existingRegistration.MappedToType;
            var uniqueId = Guid.NewGuid().ToString();
        
            // 1. Create a wrapper. This is the actual resolution that will be used
            if (lifetimeManager != null)
            {
                unityContainer.RegisterType<TDecorator>(uniqueId, lifetimeManager, injectionMembers);
            }
            else
            {
                unityContainer.RegisterType<TDecorator>(uniqueId, injectionMembers);
            }
        
            unityContainer.RegisterType<TInterface, TDecorator>();
        
            if (additionalInterfaces != null)
            {
                foreach (var additionalInterface in additionalInterfaces)
                {
                    unityContainer.RegisterType(additionalInterface, typeof(TDecorator));
                }
            }
        
            unityContainer.RegisterFactory<TDecorator>(DecoratorFactory);
        
            return container;
        
            object DecoratorFactory(IUnityContainer c)
            {
                // 3. We get the decorated class instance TBase
                var baseObj = c.Resolve(existing);
        
                // 4. We reference the wrapper TDecorator injecting TBase as TInterface to prevent stack overflow
                return c.Resolve<TDecorator>(uniqueId, new DependencyOverride<TInterface>(baseObj));
            }
        }
        

        区别在于:

        • 使用 IContainerRegistry 类型而不是 IUnityContainer - 这是因为我在 Unity 容器上使用 PRISM 包装器
        • additionalInterfaces 添加了可选参数,以便能够注册也实现其他接口的装饰器
        • 修改了逻辑,使其适合当前的 Unity API 实现

        【讨论】:

          猜你喜欢
          • 2016-07-05
          • 2018-08-04
          • 1970-01-01
          • 2012-12-17
          • 1970-01-01
          • 2015-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多