1

In my solution I have an IoC container (Ninject) in its own module. It works fine to resolve dependencies between public classes of all modules, but how could it resolve dependencies of internal classes?

I have a public class called Customer, in the BusinessRules project. Before saving a new customer, many validation methods must be called, and they're all in an internal class called CustomerValidator. This validator class is an implementation detail and should be called only to validate a new customer, so no other project should see it.

The problem is that the IoC Container can't see the CustomerValidator (since it's internal), and it can't resolve a dependency like this:

public class Customer(ICustomerValidator customerValidator)
{
//...
}

The IoC container can see only the public Customer class, but knows nothing about the existence of the internal CustomerValidator class. One possible solution is to use the InternalsVisibleTo attribute, commonly used for unit tests, and then the IoC would be able to see my internal classes:

[assembly: InternalsVisibleTo("MySolution.IoC")]

Is that an acceptable solution? Are there any other ways of doing it while keeping the CustomerValidator internal?

Glauber
  • 25
  • 7
  • What is the value of keeping it internal? Encapsulation is good, but also has its limits. – H H Jul 10 '19 at 06:46
  • Your a little unclear about where the consuming class is with respect to the validator. Same project? – H H Jul 10 '19 at 06:49
  • @HenkHolterman The idea of keeping the validator class internal is to hide an implementation detail. – Glauber Jul 10 '19 at 06:54
  • @HenkHolterman The Customer (public) and the CustomerValidator (internal) classes are in the same project. The IoC is in another project, and can see only the Customer class. – Glauber Jul 10 '19 at 06:56
  • 2
    Strongly related: https://softwareengineering.stackexchange.com/q/222707/27316 – H H Jul 10 '19 at 07:59
  • And there are links to other Q+A there. The consensus is to make the Validator public. Which sounds OK to me. Otherwise: forget about DI. DI doesn't (can't) do implementation details. – H H Jul 10 '19 at 08:07
  • @HenkHolterman Thank you, Henk. In this link I found two mentions to the InternalsVisibleTo attribute, and apparently nobody thinks it's a bad idea to use it. What do you think about using this attribute? Do you think it creates a hidden dependency between modules? – Glauber Jul 10 '19 at 08:25
  • 2
    Yes, it is a hack. Not just hidden, it is also circular. OK for unit testing, but lying to yourself otherwise. Just make the validators public. – H H Jul 10 '19 at 09:01

0 Answers0