1

We have a bunch of MVC and WebAPI projects that use dependency injection to access service classes and other dependencies like that from the controllers in both frameworks. The problem I'm having is that I wanted to make all the services specific to each project internal, but I can't because the controller classes on both frameworks need to be public, which causes compilation errors if I try to receive instances of parameters that are internal types using constructor injection.

This has bitten me more than once. It happens with almost all frameworks that call your code, be it web frameworks like WebAPI, MVC or even WebForms, and with other kinds of projects like tests, where the test classes need to be public also.

My understanding of object orientation in general is that you want to have as closed a scope as possible, so that things only have access to a minimal set of features that they need to work with. I find this a very good approach in general, because it minimizes the influence of other stuff on each class, and leads to clearer and easier to discover code.

My service classes are just that. They were created to be used just by the controllers in the same assembly, and by nobody else. By having to mark them public, I'm exposing them to external callers for no reason, and I lose a lot of important compile time information by doing so, like for instance FxCop will warn me if there is no one calling a certain method from an internal class, but it can't infer that if the class is marked public, since someone else outside of the project (or even the solution) could be using that type and calling that method.

This extends to interfaces as well obviously. As I said, we are using dependency injection (with Unity) and usually there is a interface for each service class in that scenario. Even if I can mark implementations themselves as internal, needing the interface to be public is still not ideal.

Is there some pattern that would allow me to cleanly define internal classes and interfaces but still work with external frameworks that need my outside facing classes to be public so they can call me? How should I proceed in general to make sure my code is as tightly scoped as possible?

4

1 回答 1

0

我推荐使用外观模式,这里讨论:

http://en.m.wikipedia.org/wiki/Facade_pattern

于 2015-03-26T02:05:07.567 回答