views:

362

answers:

2

Hi, 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!

+4  A: 

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

Gerrie Schenck
Thanks Gerrie and Bojan! Worked a treat.
Niall Connaughton
+1  A: 

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

container.Kernel.AddComponentInstance<IMyInterface>(serviceObj);
Bojan Resnik