How to define a Structuremap named instance in Code
Asked Answered
F

2

11

I want to create a Structuremap named instance in code, without config file

I want to be able to create the instance like this:

var namedInjector = ObjectFactory.GetNamedInstance<IInjectable>("Other");

I cant define such a type in code. I have found this sample but it uses the old syntax of a previous version and defines the named instance as:

.ForRequestedType<MementoType>()
.AddConcreteType<ConcreteType>(instanceName)

In the latest structuremap version there is no .AddConcreteType(instanceName) method which takes a instance name.

Flout answered 22/3, 2009 at 18:37 Comment(0)
N
19

I believe you need something like:

class MyRegistry : Registry {
    public MyRegistry() {
        this.ForRequestedType<IFoo>()
            .TheDefaultIsConcreteType<Bar>()
            .AddInstances( x => {
                x.OfConcreteType<Blap>().WithName("abc");
            });
    }
}
...
ObjectFactory.Configure(x=>x.AddRegistry<MyRegistry>());
IFoo test1 = ObjectFactory.GetInstance<IFoo>(); // Bar
IFoo test2 = ObjectFactory.GetNamedInstance<IFoo>("abc"); // Blap
...
interface IFoo {}
public class Bar : IFoo {}
public class Blap : IFoo {}
Neu answered 22/3, 2009 at 20:21 Comment(1)
Any idea on the new syntax for StructureMap on how to do this?Vanquish
P
1

In the words of new syntax:

            For<IEncryptionService>()
                .AddInstances(x => { x.OfConcreteType<AdvancedEncryptionService>().Named("Advanced"); })
                .Use<EncryptionService>();
Penn answered 12/9, 2013 at 8:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.