How can I use Unity with internal classes?

前端 未结 3 1494
孤城傲影
孤城傲影 2021-01-19 10:06

I have a Web API application and am using Unity for dependency injection. The application uses a library containing an Interface IDoStuff and a class that implements the int

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-19 10:25

    Forget for a moment that you are using a container and let's say that you create those classes yourself in the startup path of your application. How would you actually do this in C#?

    The answer is, you can't. This will simply not compile in C#, because C# requires those types to be public. So although those types might be an implementation detail to other components, they are not an implementation detail to the part of your application that wires them together. Whether or not you use a DI library to help you is irrelevant; that library needs access to those libraries, because to the library, those classes are not implementation details.

    And do note that there are different ways of hiding those classes. You can move the interfaces into their own assembly and let both the consuming library and the library that contains the implementations depend on that new 'contract' assembly. When you don't let the consuming assembly depend on the implementation assembly, the implementation types are effectively hidden from the consuming assembly, even though those types are still public.

提交回复
热议问题