Calling a .NET 5 (.NET Core) COM DLL from Microsoft Office (Excel, Word, Outlook, etc.)

I have finally got a .NET 5 DLL written in C# able to be called from Microsoft Office! This process actually works for any application to call the DLL through COM.This has been a bear to figure out. It is not easy, but it can be done. There are some mentions of the process on the web, but I have seen no examples. I am going to post the code on GitHub with a sample project, and the full description over there.

So before launching into the process, here is my most basic recommendation. If possible, for the time being don't use .NET 5 or .NET Core at all. Use the .NET Framework 4.x, because it does much of the work for you. For my current project, that wasn't possible, because a library it needed to call was only going to be maintained on .NET 5, as it was also being called from at .NET 5 front end. This recommendation will likely change as the .NET core does the work of providing a type library in the comhost file they create in some future release.

But here is the basic process: 1) Create a project with a class and interface. 2) Decorate them with appropriate attributes. 3) Add the appropriate method and the commands to create the correct registry entries to the project. 4) Add the appropriate settings to project file. 5) Build the DLL. 6) Create a parallel IDL file that describes the interface. 7) Compile it with the MIDL compiler. 8) Register the DLL. 9) In office, add a reference to the DLL.

There are various gotchas in this process. One of the things that is tricky is making sure that your DLL, the comhost wrapper, and the version of Microsoft Office you are calling it from all have the same bitness (32 bits or 64 bits).

So given all that, you can find the test project with more detailed documentation here: https://github.com/GregReddick/ComTestLibrary/tree/master/ComTestLibrary1

No comments :

Post a Comment

Note: Only a member of this blog may post a comment.