How to re-export types from a referenced .NET asse

2019-02-25 15:14发布

问题:

We have a big .NET project consisting of many modules, which are implemented as Visual Studio library projects and compiled into respective assemblies (DLLs).

We have a layered architecture and we manage dependencies between the modules / layers by setting references between the Visual Studio projects / assemblies. This allows us to separate APIs/SPIs from the implementations, and keep distinct layers separated, thus effectively enforcing the constraints of our architecture.

However, simetimes we wish we could (transitively) re-export the types imported in one assembly to any further assembly which has a reference to the importing assembly.

For example, suppose a type T is defined in assembly A, assembly B references A, and assembly C references B, like this:

A <-- B <-- C

We would like to 'see' the type T in assembly C, without explicitly setting the reference to A in the assembly C. We would like to somehow re-export the reference to A in B instead.

Is it possible?

P. S. Why do we want to do this? Because some types are used throuout the application (think of utility/helper classes or common interfaces) and it would be annoying to duplicate the references in every project which depends on these types. Furthermore, when we refactor our code and move these around, we get lots of error messages because of missing references.

EDIT

To clarify, here is a simple diagram.

Not only does Consumer B depend on B, but also on A, since B extends A. However, if A is defined in a different assembly than the assembly of B, then we also must add a reference to the assembly of A (the same applies to providers). But there is no actual need to add this reference, since the dependency on A follows from the fact that we depend on B and B extends A. What we really need is to somehow re-export the dependency of B on A.

How can this scenario emerge? Suppose there was only one interface B and you decided to extract common interface (A) from B and place it in a separate assembly such that some other modules can reuse the new interface without adding the dependency on the original interface. And there you go: now you'll have to add a reference to the new assembly everywhere B was used before.

回答1:

There's an attribute on assemblies in .net where you can tell an assembly that the type it is expecting to be there, would be in another.

[assembly:TypeForwardedToAttribute(typeof(Example))]

Sounds like a usage of Type Forwarding to me http://msdn.microsoft.com/en-us/library/ms404275.aspx

see also How do you explain type forwarding in simple terms?