When should [assembly: InternalsVisibleTo()] be used?
Asked Answered
M

3

15

I understand that the InternalVisibleTo attribute is used to expose types and methods with the internal access modifier to a specified assembly. I have only ever used this for exposing internal methods to a separate assembly containing a suite of unit tests.

I am struggling to think of another scenario when this should be used. Was this attribute introduced specifically to aid unit testing or was there another reason?

Margarettemargarida answered 19/7, 2010 at 8:59 Comment(0)
O
14

A scenario can be that you have separation of logic between assemblies (like internal data objects and the logic layer). You don't want to expose the classes to your users, but you still want to use the objects in your own assemblies.

I think this is not a very common scenario, I hardly ever use InternalsVisibleTo in non unit tests context.

Oriane answered 19/7, 2010 at 9:1 Comment(1)
I agree. I only use it in unit testing scenario's, but the scenario you describe is a reasonable one.Sakai
D
8

This scenario is similar to that of Elisha's, but is targeted at enforcing correct use of your domain model in Domain-driven design.

Let's say you have an assembly MyProject.Core, which contains all of your domain models. If you don't want other people directly creating instances of your domain models, you can make the constructors internal.

Another assembly, called MyProject.Services, contains domain services that are specialized in creating valid domain objects. This assembly will have a reference to MyProject.Core. The InternalsVisibleTo attribute is used to grant the domain service assembly access to the internal constructors.

Another benefit of the reference from MyProject.Services to MyProject.Core is that it disallows the domain objects to keep any references to domain services, which is considered another good DDD practice.

Note: I have never applied the above scenario in practice, so it may not be completely accurate on the DDD level. But this is a use of InternalsVisibleTo that I could think of, that isn't unit test related.

Dionisio answered 19/7, 2010 at 21:8 Comment(0)
S
6

Apart from testing, the only other scenario I've ever used the InternalsVisibleTo attribute, was when creating serialization assemblies.

Other than that, I've never used, nor needed it.

Shantung answered 19/7, 2010 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.