Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying instance for registration of a component with Castle Windsor

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!

like image 831
Niall Connaughton Avatar asked May 29 '09 09:05

Niall Connaughton


1 Answers

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)

like image 143
Gerrie Schenck Avatar answered Sep 20 '22 06:09

Gerrie Schenck