Having worked with Spring MVC for JAVA, I’ve gotten used to having @Transactional behaviour being applied in the service layer which works fabulously well with Hibernate DAOs.
Now that I’m faced with a similar challenge in a project which is based on LINQ to SQL ORM, I see that all transactions are taking places within DAOs ( i.e. using (DC dc = new DC() { dc.submitChanges()}
How do you remove transaction logic from DAOs and bring it to the service layer in ASP.NET MVC LINQ2SQL project?
Thank you.
It worked fabulously because Spring MVC had Hibernate’s
SessionandSessionFactoryregistered and dealt with creating and committing transaction. You can do it in .NET as well but you must do it yourselves. There is no prepared integration of all these tools like Spring MVC provides to Java. You generally need to injectDataContextinstance into service layer instead of creating it manually.What you call service layer? For me the service layer is a model. In such case the stuff is mostly outside of ASP.NET MVC – there is a way how to create attribute for controller’s action in ASP.NET MVC (custom filters) but that is not a service layer. If you want custom transactional attribute for service layer it mostly means Aspect oriented programming (AOP).
What are your choices? Select good IoC container which supports AOP – fore example Windsor Castle, Spring.NET, Unity 2.0 or use PostSharp for AOP. The easy way to make transactional AOP attribute is just creating
TransactionScopebefore the annotated method is executed andCompletethe scope after the annotated method is executed. But that is not what you want because you will still have to createDataContextinstance and callSubmitChanges. You need AOP attribute which will createDataContextinstance store it somewhere and execute annotated method. The method will be able to load stored context instance and use it. Once the method finishes the AOP attribute will callSubmitChanges. The only problem is where to store the context instance and how to retrieve it – I believe Spring MVC uses Spring internally for this and provides the whole infrastructure but in .NET you will have to write it – in case of Web app. you will have to store the context inHttpContext.Items.