Specifying instance for registration of a component with Castle Windsor

12,130

Solution 1

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)

Solution 2

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

container.Kernel.AddComponentInstance<IMyInterface>(serviceObj);
Share:
12,130
Niall Connaughton
Author by

Niall Connaughton

Software developer from Sydney, now in Seattle. http://blog.niallconnaughton.com/

Updated on June 05, 2022

Comments

  • Niall Connaughton
    Niall Connaughton almost 2 years

    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!