Moving a type from one assembly to another using TypeForwardedToAttribute
One of the problems that we’re facing today in the Framework, mainly stemming from the red bits/green bits design of .NET 3.5, is that certain ‘core’ types are located in the wrong assemblies.
For example, the extremely useful ObservableCollection<T> and ReadOnlyObservableCollection<T> types both live in WindowsBase.dll, which is a part of the Windows Presentation Foundation. For low-level assemblies (such as my team’s very own System.ComponentModel.Composition.dll), this means that to use types such as these, they need to take a reference to assemblies either at a higher level to themselves, or to technologies outside of their own. This is in turn leads to scary dependencies, such as the server assembly System.Web.dll’s current direct dependency on the client assembly System.Windows.Forms.dll in .NET 2.0.
Going forward for .NET 4.0, the Framework Architecture team will be leading an effort (being pushed by my colleague Mitch Trofin) to move these and other core types to lower-level assemblies such as mscorlib.dll and System.dll.
Now, as I’ve mentioned previously, Microsoft takes compatibility very seriously, so you might be thinking ‘how can they move these types without runtime breaking changes’?
Luckily, there’s already a solution for this; type forwarding. Introduced in .NET 2.0, type forwarding allows assembly writers to move types into other assemblies without needing existing consumers to recompile their applications. This done via the TypeFowardedToAttribute.
To move a type, do the following:
- Move the type from the original assembly to the assembly that will become the type’s new home.
- In the original assembly, add a reference to the new assembly if it does not already have one.
- Apply the following assembly-level attribute to the original assembly, replacing MyType with the type you moved in step 1:
- Compile both assemblies and that’s it.
A couple of things to note:
- The type must have the same name and namespace in the target assembly.
- This is considered a source breaking change; that is, users recompiling their application against the new versions of the assemblies, will be required to add a reference to the assembly that now contains the type.
- While fully supported by C# and C++/CLI, Visual Basic does not support moving types using the TypeForwardedToAttribute. It does, however, support consuming assemblies written by other languages that have had their types moved.
- Starting in .NET 4.0, a new attribute called TypeForwardedFromAttribute should be applied to types that have been forwarded indicating which assembly they came from. This allows runtime serialization to serialize these types correctly when interoping with previous versions of these assemblies.