Fork me on GitHub

Registering Existing Objects Edit on GitHub


It's frequently common to register existing objects with a StructureMap Container and there are overloads of the Registry.For().Use(object) and Registry.For().Add(object) methods to do just that:


[Fact]
public void should_be_able_to_resolve_from_the_generic_family_expression()
{
    var widget = new AWidget();
    var container = new Container(x => x.For(typeof(IWidget)).Use(widget).Named("mine"));

    container.GetInstance<IWidget>("mine").ShouldBeTheSameAs(widget);
}

Injecting an existing object into the Container makes it a de facto singleton, but the Container treats it with a special scope called ObjectLifecycle if you happen to look into the WhatDoIHave() diagnostics.

StructureMap will attempt to call the IDisposable.Dispose() on any objects that are directly injected into a Container that implement IDisposable when the Container itself is disposed.