Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register named instance in ObjectFactory

Tags:

structuremap

I try to register named instances in structure map. But my trials are not successful.

What is the correct way?

Currently I'm doing it like this:

IService bus = CreateInstanceOfServiceBus();
ObjectFactory.Configure(cfg => cfg.For<IServiceBus>()
                                  .AddInstances(x =>x.IsThis(bus)
                                  .Named("foobar"))
                                  .Singleton());

But when I try to get the named instance, nothing is found:

ObjectFactory.TryGetInstance<IServiceBus>("foobar");

Thanks in advance. Best regards.

Joachim

like image 469
Joachim Rosskopf Avatar asked Jan 01 '26 11:01

Joachim Rosskopf


1 Answers

You can simply register as follows

IServiceBus bus = CreateInstanceOfServiceBus();
ObjectFactory.Initialize(x => x.ForSingletonOf<IServiceBus>().Use(bus).Named("bus")); 

Now you can resolve the instance either like this

ObjectFactory.GetNamedInstance<IServiceBus>("bus");

or

ObjectFactory.TryGetInstance<IServiceBus>("bus");

You are using the Configure method which simply adds another configuration to the container. Consider if you will change to Initialize, which initializes a new configuration.

like image 102
Jan Christian Selke Avatar answered Jan 05 '26 23:01

Jan Christian Selke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!