Is dependency injection useful in C++

前端 未结 5 1459
暗喜
暗喜 2021-01-31 02:39

C# uses Dependency Injection (DI) a lot to have a lossless and testable platform. For this, I need

5条回答
  •  后悔当初
    2021-01-31 03:20

    If my theory with references are correct, is there something like a container where I can resolve all the references? In C# I have a "bad class/bad project/assembly" which registers all my instances into a static container at the program start. Then, in every class, I'm able to instance the static container and can resolving a specific instance, is this possible in C++?

    That's not how DI is supposed to be used, you don't pass your container to all your "consumer" class. In a well designed application you just do few resolve in the entry point and that's it. Most of the time the need for a "resolve" can be replaced by the use of a factory which will be registered then injected.

    You'll have a lot of trouble testing code depending on a static class. I would recommend if you really want to inject your container in your client class to at least instance and inject it, static dependencies are hell, would be easier to mock for unit testing.

提交回复
热议问题