IoC - Multiple implementations support for a single interface

后端 未结 7 1452
清歌不尽
清歌不尽 2020-12-30 02:50

I am wondering why .Net IoC containers do not easily support multiple implementations for a single interface! May be I am wrong, but as far I have seen, frameworks like Nin

7条回答
  •  醉梦人生
    2020-12-30 03:16

    Your question is a bit vague, since you don't supply a concrete example of when you think you need this. In most cases there is a problem in your application or design, or you aren't following DI best practices.

    All containers allow you to register multiple dependencies with the same interface as an IEnumerable, even if they do not have deep support for multiple instances. Injecting lists of services into other services however, is a design smell, and it would be better to hide this list behind a Composite. This hides the fact that there are multiple implementations behind the abstraction, and allows you to easily change the way those multiple implementations are used, by changing just a single place in the application. I don't believe any IoC framework has any support for generating composites for you, since the there is no one default way of processing the wrapped implementations. You'll have to write this Composite yourself. However, since writing such a composite is really, really simple, this justifies not having such feature in the framework.

    If you want to have multiple implementations, but always need one to be returned, based on some configuration, there are always ways to do this. Most containers allow you to configure those dependencies in an XML configuration file. But even if a container does not contain such feature, reading this value from the configuration file manually and registering the right type in the container is very easy.

    If you have one implementation of a certain interface for production and another implementation for unit testing purposes, you should only register the production implementation in the container. Your unit tests should be clear of any DI container, and you should manually create a class under test, and inject fake dependencies in its constructor, by simply newing the type up. Using a DI container, pollutes and complicates your tests. To pull this off, you will need to design such type around the constructor injection pattern. Don't call the container (or any other facade over the container) inside the service under test, to retrieve dependencies.

提交回复
热议问题