0

I have a ASP.Net MVC 3 photo gallery, which is designed in this way:

Data Repositories(IImageRepoSitory, ITagRepository etc)
      |
   Services (IGalleryService, IWebService etc)
      |
  Web Application

Which I use Ninject to inject the required Services and repositories into the web application.

Before I use actual database, I used a simple ArrayList (and JSON serialization) as my presistent logic (That will be JsonImageRepository/JSonTagRepository) which works perfectly fine. But later on, I moved to EF4 CTP5 (Code First), and many problems appeared. Basically, I injected those repositories and services as Singleton (which declared in Global.asax.cs), but when I have several threads that access the repositories, it saids:

Data Connection is closed.

I changed to something like Thread Mode or Request Mode in Ninject but various exception raised (regarding to multiple instances of context, so I think Singleton should be the only option).

Is there anything wrong with the design? or how should I configure those components?

xandy
  • 27,357
  • 8
  • 59
  • 64

1 Answers1

4

Normally, repository access should be in request scope (at least the ones that change data). I recommend looking at bob's blog posts about a repository pattern implementation using Ninject and NHibernate. It should be pretty much the same for EF4:

http://blog.bobcravens.com/2010/06/the-repository-pattern-with-linq-to-fluent-nhibernate-and-mysql/

http://blog.bobcravens.com/2010/07/using-nhibernate-in-asp-net-mvc/

http://blog.bobcravens.com/2010/09/the-repository-pattern-part-2/

I planned adding this to the sample application in near future.

Remo Gloor
  • 32,665
  • 4
  • 68
  • 98
  • That means the Repository should be created every time a new request is made, and the Service layer that depends on IRepos should also in request scope, is it? – xandy Feb 07 '11 at 15:14
  • that's right. you will also want to open a Transaction when the request begins and Commit or Rollback the Transaction when the request ends. – Dave Thieben Feb 08 '11 at 18:37
  • Just one more follow up question. In such case, the Entity Object cannot live longer than one request cycle, that means, if for some reason I need to cache the Entity object in Session, it's not possible other than duplicating it, right? – xandy Feb 10 '11 at 05:23