Specifying instance for registration of a component with Castle Windsor
Asked Answered
D

2

20

I have what is probably a simple question here about Castle Windsor, which I haven't been using for very long. I'm trying to register a service with a specific instance that will be the singleton implementation of the service.

The container cannot try to create the implementation of the service itself because it has dependencies that the container will not be able to resolve. I have an instance of the service and I want that to be the one and only instance used for anyone requesting the service. But I appear to be having very little luck.

I momentarily had hopes raised by using this code:

container.Register(Component.For<IMyInterface>().Instance(serviceObj));

But all Castle does with the instance is do a .GetType() on it and register the type. Requests for the service will subsequently cause the container to try to create that type and fail when it can't fill the dependencies.

So is there any way to do what I want to do here? If not I will create some kind of IServiceProvider that fetch the instance of the service and have no dependencies for the container to fill out. But this feels like more of a work around than the right solution.

Any suggestions? Thanks!

Dunton answered 29/5, 2009 at 9:53 Comment(0)
L
31

Try using the AddComponentInstance method on the container's Kernel object. I think this is what you need.


Please note: This technique is now deprecated. Use container.Register(Component.For<T>().Instance(myT)); instead (thanks to eouw0o83hf)

Longship answered 29/5, 2009 at 10:2 Comment(4)
Thanks Gerrie and Bojan! Worked a treat.Dunton
As a brief note, this technique is now deprecated. Use container.Register(Component.For<T>().Instance(myT)); instead.Vitrescent
That link's also dead nowValero
having issues adding instance to a interface. works when i try to register it as a concrete classHelvetic
G
3

You can do that through the Kernel property of the container:

container.Kernel.AddComponentInstance<IMyInterface>(serviceObj);
Gilbert answered 29/5, 2009 at 10:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.