views:

590

answers:

2

Hi,

I want to register a specific instance of an object for a type in structuremap, how can I do that?

For example,

When I do:

var myObj = ObjectFactory.GetInstance(typeof(MyAbstractClass));

i would like it to return a previously constructed concrete class, which i created like this:

var myClass = new MyConcreteClass("bla"); // MyConcreteClass : MyAbstractClass

so

myObj == myClass

How do i register myClass with structuremap to facilitate this?

Thanks

Andrew

+2  A: 

I believe you would do this in you initialization

        ObjectFactory.Initialize(x =>
        {
            x.ForRequestedType<MyAbstractClass>().TheDefault.IsThis(myClass);
        });

Where myClass is the instance of the object you want to return.

Jab
Im getting: Type instance MyConcreteClass cannot be plugged into type MyAbstractClass. Any idea?
Andrew Bullock
Have you gotten this to work? I just looked back and noticed your reply. I haven't had any issues doing it this way in our application. Do you get a compile error or a initialization error? You might post the code that is trying to get the instance.
Jab
+2  A: 

You can inject a concrete instance as the default by

ObjectFactory.Inject(typeof(MyAbstractClass), myClass);
Markus Dulghier
This worked well for me. I have a couple of instances of an ISessionFactory that I set up. Each has a name because each points to a different database. After the initial ObjectFactory.Initialize() I then add your code to tell StructureMap that my IWorkorderRepository should point to the correct database:ObjectFactory.Inject(typeof (IWorkorderRepository), new WorkorderRepository(ObjectFactory.GetNamedInstance<ISessionFactory>(Resources.CityworksDatasource)));
Dylan