It is possible to lazily resolve a component in Castle Windsor by registering LazyOfTComponentLoader in the container and resolving a Lazy<T>
as specified here:
container.Register(
Component.For<ILazyComponentLoader>().ImplementedBy<LazyOfTComponentLoader>(),
Component.For<ISomeService>().ImplementedBy<ServiceImpl>().LifestyleTransient()
);
var lazy = container.Resolve<Lazy<ISomeService>>();
lazy.Value.DoSomething();
However, is it possible to register a component in the container so that it is always resolved as a Lazy<T>
without the need to specify Lazy in the resolve call?
Specifically, I'm wondering how to inject Lazy components into controllers in an MVC project when using constructor injection.
EDIT: You can specify Lazy<ISomeService> someService
as a parameter in the controller's constructor as can be seen here. However, is there a way of ensuring that a component is resolved lazily through the registration process?
If you want to resolve a lazy loaded instance of component, you will need to do a Resolve<Lazy<ISomeService>>()
. The function lazy.Value, will do the actual resolving of the component. If you would do a resolve you will directly get your component.
If you really want to have a component which is resolved only upon first use without the use of Lazy, you could resort to writing an interceptor.
Good luck, Marwijn.