Search code examples
inversion-of-controldryioc

DryIoc - Register Single for an existing object already created


Is it possible to achieve something like this;

var myObjectInstance = new MyObject(); // We have an instance of a class.

Container.Register< IMyObject, MyObject >(Reuse.Singleton, myObjectInstance); // For example register it 

var myObjectInstance2 = Container.Resolve< IMyObject>(); // Then resolve it

Right now they should be equal myObjectInstance = myObjectInstance2

Can we do it? I didn't get success.


Solution

  • Like this:

    var myObjectInstance = new MyObject();
    
    Container.UseInstance<IMyObject>(myObjectInstance);
    
    var myObjectInstance2 = Container.Resolve<IMyObject>();
    Debug.Assert(myObjectInstance == myObjectInstance2);
    

    Here is the docs.