Appropriate lifecycle for repository classes using Castle Windsor

后端 未结 2 705
暖寄归人
暖寄归人 2020-12-21 19:15

When I started with Windsor I thought DI would be simple. Now it\'s causing me more and more confusion.

A repository strikes me as a class with a singleton lifecycle

相关标签:
2条回答
  • 2020-12-21 19:18

    Rule of thumb is - component should not depend on other components that will outlive it.

    In other words, it's ok for transient to depend on singleton, or per-web-request component, but not the other way around.

    The way I approach Repository - UoW scenario is my UoW is per web request, but repositories are stateless and transient.

    0 讨论(0)
  • 2020-12-21 19:28

    When you say repository, I assume you mean a repository which abstracts an Nhibernate session. If so, then it should never ever be singleton. If it is a singleton, then multiple request threads will trample over one another's session. I personally have seen a few defects around this. Since Castle's default life cycle is singleton, if a developer forgets to explicitly mark a component's life cycle, bad things start happening.

    It should ideally be per-request (following the unit of work concept). The only rider to this approach is that you have enable Asp.net compatibility mode in your application (if it's not Asp.net that is). The other way is to mark a repository transient. But the downside to this approach is that Castle will instantiate a new repository object every time a component needs it.

    0 讨论(0)
提交回复
热议问题