开发者

Generate an ID via COM interop

开发者 https://www.devze.com 2022-12-31 00:48 出处:网络
At the moment, we\'ve got an unmaintanable ball of code which offers an interface to a third party application. The third party application has a COM assembly开发者_开发知识库 which MUST be used to cr

At the moment, we've got an unmaintanable ball of code which offers an interface to a third party application. The third party application has a COM assembly开发者_开发知识库 which MUST be used to create new entries. This process involves two steps: generate a new object (basically an ID), and update that object with new field values.

Because COM interop is so slow, we only use that to generate the ID (and related objects) in the database. The actual update is done using a regular SQL query.

What I am trying to figure out if it's possible to use NHibernate to do some of the heavy lifting for us, without bypassing the COM assembly. Here's the code for saving something to the database as I envision it:

using(var s = sessionFactory.OpenSession())
using(var t = s.BeginTransaction())
{
    MyEntity entity = new MyEntity();
    s.Save(entity);
    t.Commit();
}

Regular NH code I'd say. Now, this is where it gets tricky. I think I have to supply my own implementation of NHibernate.Id.IIdentifierGenerator which calls the COM assembly in the Generate method. That's not a problem. What IS a problem is that the COM assembly requires initialisation, which does take a bit of time. It also doesn't like multiple instances in the same process, for some reason.

What I would like to know is if there's a way to properly access an external service in the generator code.

I'm free to use any technique I want, so if it involves something like an IoC container that's no problem. The thing I am looking for is where exactly to hook-up my code so I can access the things I need in my generator, without having to resort to using singletons or other nasty stuff.


Assuming you want a single instance of the COM component for all of your entities, a Service Locator (implemented with any IoC container) is the way to go.

Your (trivial) IIdentifierGenerator implementation would have to call the locator in its constructor to get the component instance, and call the corresponding method on the component on Generate.

One thing to consider: is the COM component thread-safe? If not, you should synchronize the Generate calls.

Usage of the generator is simple, just use the fully-qualified name as your generator class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号