I’m wondering what the best practice is for Castle Windsor component dependency lifestyles. For example if I have a Repository class that is dependent on an ISession. If the Repository is set as PerWebRequest, but the ISession is set as transient, will this pose any problems for the windsor releasing the components so the GC can correctly clean up?
Logically this seems like it will work, because every request for a Repository during the webrequest will get a reference to the same instance. That instance will hold a reference to the single ISession that was instantiated to satisfy the Repo dependency when it was first requested. Windsor will know when the Repo is out of scope due to the PerWebRequest tracking, and thus should know when to clean up the ISession.
However, this post by Krzysztof Koźmic implies that you shouldn’t have a component dependent on something with a shorter lifestyle than itself.
[edit]
My question is, is it acceptable to have a Windsor Component depend on something with a shorter lifestyle than itself (i.e. PerWebRequest component -> Transient component)?
Yes, it can be perfectly fine, especially in case of
something --> transient. The things you need to worry about is:If you’ve considered those two, and potentially a number of other factors specific to your scenario, you’re in a good position to make an informed choice to press on with the dependency.
Alternatively you can make it a transitive dependency via a layer of indirection:
singleton -(depends on)-> singleton factory -(resolves)-> per-web-request component.A singleton object may depend on a factory which it uses to pull, say, per-web-request objects that it uses to do its job. With that, if implemented properly, it won’t have the drawbacks discussed above.
Hope that helps.
Oh, and the other answer of mine, you linked to in your question – it says rule of thumb, not strict law. It’s probably right in majority of cases, but, as discussed above, it’s fine to break it if you know what you’re doing. That’s also the reason why Windsor’s diagnostic for detecting those cases is called Potentially misconfigured components