June 03, 2010

Interop Assemblies

What the hell are these Interop Assemblies, Primary Interop Assemblies (PIAs)?

You'll see these assemblies from time to time pulled in as references in you projects, but I never really cared why they were called Interop and what it meant, I'll explain.

Interop is short for interoperability meaning how to get .NET to talk to COM.

Primary Interop Assembly (PIA):
A PIA is an interop assembly that is signed by the originator to mark it as the one and only assembly to use to get the Type information. It's used to avoid conflicting Types. The assembly is signed in a particular way using the tlbimp.exe and then used by the client to resolve Types.

What have they got to do with COM?
So implementations and Types available through COM is not accessible itself through .NET itself in the usual manner i.e. you cannot new up objects etc because you do not know the Type names. To get over this the COM Types are wrapped into an Interop Assembly. Interop is short for interoperability meaning how to get .NET to talk to COM.
So using some mechanism we want to extract all the Type information on the COM Types into a nice assembly which we can then pass around as references to let clients know what Types are available from COM. One tool we can uses is tlbimp.exe. This tool is ran against the COM Type and results in an assembly with all the Type information of those COM Types found, it does not contain the implementations, they still exist in COM.
The usefulness of this is you can add a reference to this Interop assembly to you .NET project in Visual Studio and then us the Types like ordinary .NET types allowing you to new up objects etc without having to worry about the COM mechanism which runs in the background.

What is TLB and a .tlb file?
tlb stands for Type Library. A .tlb file is a file that contains the COM Type information. The COM Type information does not have to be in a .tlb file, it can also be in an assembly or other file types such as .ocx or .olb.
A tlb file can be generated using the tlbimp.exe http://msdn.microsoft.com/en-us/library/tt0cf3sx.aspx

What does the "Embed Interop Type" property do in Visual Studio?
In .NET 4, Visual Studio 2010, you have the ability to include references to Interop Assemblies with the property "Embed Interop Type" (you'll see then in the assemblies properties window after you add the reference). This is known as "design-time-only interop assemblies". This embeds the interop type information into the current executable/assembly, the benefit is you do not have to redeploy the interop assemblies with your application afterwards. This is handy as when using installers etc you usually have to copy the interop assemblies to the clients machine, this new mechanism removes that requirement.