Can an IActivationFactory return the same instance multiple times?

197 views Asked by At

While exploring WinRT, I made an experiment with singletons: by implementing the IActivationFactory myself, I can make a singleton "at the ABI level". The factory just returns the same instance every time. By extension, any call to RoActivateInstance for my type will return the same pointer.

It is curiously almost transparent when interoperating with .NET:

var obj1 = new MySingleton();
var obj2 = new MySingleton();

// At the .NET type level, not the same: ReferenceEquals(obj1, obj2) == false
// At the COM level, the same: Marshal.GetIUnknownForObject(obj1) == Marshal.GetIUnknownForObject(obj2) 

The way I interpret this is that every instantiation generates a new RCW for the WinRT object. Thus it's not exactly the same as a singleton, but maybe close enough.

I haven't examined the other language projections.

My intention is to use this for immutable objects, which may not even have any constructor parameters. (If they do, the activation factory will need to keep a map of instances.) The benefit is mainly the reduced memory footprint.

But am I treading dangerous waters here? I have seen similar constructs in COM/ATL, but what about in WinRT?

0

There are 0 answers