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

后端 未结 7 736
一整个雨季
一整个雨季 2020-12-01 03:09

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 y

7条回答
  •  無奈伤痛
    2020-12-01 03:38

    Another approach, thanks to a suggestion from @DarkSquirrel42, is to use an InjectionFactory. The downside is that the code still needs updating every time a new constructor parameter is added to something in the chain. The advantages are much easier to understand code, and only a single registration into the container.

    Func createChain = container =>
        new LoggingProductRepository(
            new CachingProductRepository(
                container.Resolve(), 
                container.Resolve()), 
            container.Resolve());
    
    c.RegisterType(new InjectionFactory(createChain));
    Assert.IsInstanceOf(c.Resolve());
    

提交回复
热议问题