How can I wrap a COM object in a native .NET class?

后端 未结 4 1026
醉梦人生
醉梦人生 2021-02-05 10:53

I\'m using an extensive existing COM API (could be Outlook, but it\'s not) in .NET (C#). I\'ve done this by adding a \"COM Reference\" in Visual Studio so all the \"magic\" is

4条回答
  •  滥情空心
    2021-02-05 11:26

    It sounds like you are looking to create a simpler .NET API around your complex COM API. As nobugz said, your ComObject classes are real, native .NET objects that internally contain the unmanaged references to your actual com objects. You don't need to do anything funky to manage them...just use them like they are normal .NET objects.

    Now, in regards to presenting a "prettier face" to your .NET consumers. There is an existing design pattern for this, and its called a Facade. I am going to assume that you only really need a part of the functionality that these COM objects provide. If that is the case, then create a facade layer around your com interop objects. This layer should contain the necessary classes, methods, and support types that provide the neccesary functionality to all of the .NET clients with a friendlier API than the com objects have themselves. The facade would also be responsible for simplifying oddities like converting whatever the com objects do for events with normal .NET events, data marshaling, simplification of com object creation, setup, and teardown, etc.

    While in general, abstractions should be avoided, as they tend to add work and complexity. However sometimes they are necessary, and in some cases can greatly simplify things. If a simpler API can improve the productivity of other team members who need to consume some of the functionality provided by a very complex com object system, then an abstraction provides tangible value.

提交回复
热议问题