开发者

Register named instance in ObjectFactory

开发者 https://www.devze.com 2023-04-05 00:12 出处:网络
I try to register named instances in structure map. But my trials are not successful. What is the correct way?

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>("开发者_如何学Cfoobar");

Thanks in advance. Best regards.

Joachim


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消