IoC: Existing runtime objects rather than containe

2019-08-31 03:51发布

问题:

In my case I am using Castle Windsor as my IoC container.

I would like to declare a component, where one of the constructor arguments will be set to an existing object at runtime, rather than having the IoC container create the object when it creates the component. For example, the instance of my application's main form.

I suspect there are two approaches:

  1. Create the object via the container for the first time, then configure it with any necessary runtime values so that when the component later on asks Windsor for it, it is ready to use.
  2. Create an IFormProvider and concrete FormProvider, where the component requires an IFormProvider value to be injected, which it subsequently asks for the form instance (i.e. formProvider.Form).

Any advance on this?

回答1:

This is trivial to do with Unity and its Fluent interface; just call the RegisterInstance method of the container. There's a nice discussion of this at Setting Up the Unity Container (for v1.1, but 1.2 should be similar).

I haven't used Castle Windsor, but apparently AddComponentInstance is the equivalent. See Can you register an existing instance of a type in the Windsor Container.