C#学习教程:使用WindsorShare进行通用存储库生命周期配置我有实现Repository的通用存储库,其中T是实体类型,它有一个依赖项IDatacontextProvider,它为其提供数据上下文:publicclassRepository:IRepositorywhereT:class{protectedDataContextDataContext;公共存储库(IDataContextProviderdataContextProvider){DataContext=dataContextProvider.DataContext;}....}对于简单的事情,以下配置工作正常:}ISimpleService{publicSimpleService(IRepository,IRepository){....}}我可以使IDataContextProvider成为单例,但我认为这会产生更大的问题。我可以将IDataContextProvider传递给SimpleService,并尝试在那里解析存储库实例,但这需要额外的代码来使服务易于测试,并且需要额外的依赖项。可能有人对如何解决这个问题有更好的想法?更新:根据建议,我创建了存储库工厂(它与建议的答案有点不同,它不直接依赖于数据上下文,但想法非常相似):publicinterfaceIRepositoryFactory{IRepositoryGetRepository()whereT:class;}publicclassRepositoryFactory:IRepositoryFactory{privatereadonlyIDataContextProviderdataContextProvider;publicRepositoryFactory(IDataContextProviderdataContextProvider){this.dataContextProvider=dataContextProvider;}publicIRepositoryGetRepository()whereT:class{returnnewRepository}er(dataContextbetweenthem)层,比如RepositoryFactory?那个人可能有一种短暂的生活方式。从工厂创建的所有存储库将共享相同的DataContext实例。您还需要更改存储库类,以便它们采用DataContext实例而不是DataContextProvider。公共类RepositoryFactory:IRepositoryFactory{protectedDataContextdataContext;公共RepositoryFactory(IDataContextProvider提供者){dataContext=dataContextProvider.DataContext;}publicIRepositoryGetRepository(){returnnewRepository(dataContext);}}publicclassSimpleService:ISimpleService{publicSimpleService(IRepositoryFactoryfactory){....}}IDatacontextProvider听起来像工厂接口,这些通常在依赖注入中定义为单例。我看到了几种可能的解决方案:我不知道您的应用程序的详细信息,但也许您可以为IDatacontextProvider编写自己的生活方式管理器(因为您既不说单例也不说单例)。如果您想确保在存储库之间传递相同的IDatacontextProvider,您可能应该考虑将其显式提供为方法参数,而不是注入依赖项。@Can的回答也是一种可能的解决方案,我用过一次。你的问题出在生活方式的配置上。我也有同样的问题。您必须使用PerWebRequest生活方式配置存储库。这给了我一个很好的性能提升,并将我的错误从几十个减少到零。在我的博客上,您可以找到一个结合了mvc3和EF代码的依赖注入的简单示例http://marcofranssen.nl。以上就是C#学习教程:使用Windsor的通用版本库生命周期配置分享全部内容。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
