Unity Container Multiple Implementations of same interface

前端 未结 2 1080
鱼传尺愫
鱼传尺愫 2020-12-31 12:14

I\'m studying up on the unity containers and have a quick question on how to resolve a class\'s construction to multiple different implementations of an interface.

H

2条回答
  •  鱼传尺愫
    2020-12-31 12:38

    The problem is that you are resolving Canvas with the name "GL", but you have not registered Canvas in that way. Unity doesn't propagate the name to dependency resolution, so it won't use the name "GL" when resolving IRenderer.

    There are several options to solve this already answered: Resolving named dependencies with Unity

    Your question is whether this is a bad practice, or how you can achieve the same results. In my experience, trying to register and resolve multiple instances of the same interface usually leads to messy code. One alternative would be to use the Factory pattern to create instances of Canvas.

    Do you need to use your container to resolve Canvas? If you don't have a reason not to, you could simply Resolve your IRenderer and new up a Canvas yourself:

    new Canvas(container.Resolve("GL"));
    

    Remember that Unity is just a tool, if it doesn't seem to be capable of doing what you need, you may need a different kind of tool.

提交回复
热议问题