Castle Windsor: Reuse resolved component in OnCreate, UsingFactoryMethod or DynamicParameters
Posted
by shovavnik
on Stack Overflow
See other posts from Stack Overflow
or by shovavnik
Published on 2010-04-30T19:30:20Z
Indexed on
2010/04/30
19:37 UTC
Read the original article
Hit count: 244
ioc-container
|castle-windsor
I'm trying to execute an action on a resolved component before it is returned as a dependency to the application.
For example, with this graph:
public class Foo : IFoo { }
public class Bar {
IFoo _foo;
IBaz _baz;
public Bar(IFoo foo, IBaz baz) {
_foo = foo;
_baz = baz;
}
}
When I create an instance of IFoo, I want the container to instantiate Bar and pass the already-resolved IFoo to it, along with any other dependencies it requires. So when I call:
var foo = container.Resolve<IFoo>();
The container should automatically call:
container.Resolve<Bar>(); // should pass foo and instantiate IBaz
I've tried using OnCreate, DynamicParameters and UsingFactoryMethod, but the problem they all share is that they don't hold an explicit reference to the component: DynamicParameters is called before IFoo is instantiated. OnCreate is called after, but the delegate doesn't pass the instance. UsingFactoryMethod doesn't help because I need to register these components with TService and TComponent.
Ideally, I'd like a registration to look something like this:
container.Register<IFoo, Foo>((kernel, foo) => kernel.Resolve<Bar>(new { foo }));
Note that IFoo and Bar are registered with the transient life style, which means that the already-resolved instance has to be passed to Bar - it can't be "re-resolved".
Is this possible? Am I missing something?
© Stack Overflow or respective owner