简体   繁体   中英

Multiple Instances of the Same Type

Using StructureMap, let's say I configure a couple of instances for a given interface, identified by names:

registry.For(interfaceType).Add(firstType).Named(firstName);
registry.For(interfaceType).Add(secondType).Named(secondName);
registry.For(interfaceType).Use(defaultType);

This works well for my needs. However, in some application scenarios I have cause to override an instance to use the same concrete type as another instance. So effectively going with something like this:

registry.For(interfaceType).Add(defaultType).Named(firstName);
registry.For(interfaceType).Add(defaultType).Named(secondName);
registry.For(interfaceType).Use(defaultType);

In practice, however, it would seem that StructureMap then uses not just the same type, but the same instance. So there is exactly one instance of defaultType in memory, which the container supplies for any named request.

Is there a way to tell it to construct and use separate instances even when they're the same concrete type?

This is not the behaviour I am seeing:

ObjectFactory.Configure(cfg =>
{
    cfg.For<IFoo>().Add<Foo>().Named("Foo1");
    cfg.For<IFoo>().Add<Bar>().Named("Foo2");
    cfg.For<IFoo>().Use<Foo>();
});

var foo1 = ObjectFactory.GetNamedInstance<IFoo>("Foo1");
var defaultFoo = ObjectFactory.GetInstance<IFoo>();

Debug.Assert(!Object.ReferenceEquals(foo1, defaultFoo));

Here the named instance and the default instances are different .

You are passing a type and not an object (which would be treated as singleton) in your StructureMap registration?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM