Using database transactions in ASP.NET MVC3 with Ninject DI
I'm starting a new project and want to do things better than I've done before. I used Windsor for DI but it didn't go great. I've been eyeing up using the NuGet Ninject MVC 3 package to take care of DI.
I've Googled around for many hours and found lots of helpful advice about Ninject (especially liking the filters DI stuff) but nothing that really answers the following burning scenario...
Scenario:
- I have a开发者_如何学运维 SQL Server database for persistence. I want all access to the database to be in a transaction.
- I'll be using repositories to access domain objects that are stored in the database.
- A controller might need to use multiple repositories to do it's work and hence the data access needs to be the same instance based to each repository to avoid locking issues.
- The data access should be per request made to web app.
My confusion/pondering:
- If Ninject shoves in an appropriate DB factory or context to all my repositories then where (and how) would I put code to commit on successful completion or rollback if an exception occurs? Ideally you wouldn't want to do this for every controller action so I'm guessing in the global asax EndRequest event but how to know whether to commit or rollback.
Check out Sharp Architecture's implementation of this - although they use Windsor, the same approach can be used with Ninject.
Basically you add Transaction
attributes where required on Controller methods - the plumbing is all handled by the Sharp Arch framework.
精彩评论