Linq + Unity + AOP = Fun

I've recently had some time to look at using Dependency Injection alongside of Linq to SQL to manage the DataContext. Because of the way that Microsoft made Linq to SQL, it's not very easy to use dependency injection properly with the DataContext because many of the members in this framework are not interfaces or cannot be instantiated directly from code. Type mocking frameworks can be used to mock these objects but i wanted to see if there was a way around all of this. I've posted a project on the CodeProject website here. A few tricks had to be implemented like creating an interface for the DataContext (IDataContext) and exposing a new property called GetITable exposing a new interface called IEnumerableTable<>. This way, you can resolve IEnumerableTable's from the IDataContext instead of resolving a System.Data.Linq.Table from the GetTable<> method (which you would never be able to implement in a custom DataContext class). Because the IEnumerableTable<> interface is IEnumerable<T> itself, you can run all your normal Linq queries against it as per normal. IEnumerableTable<> also implements ITable so you can perform all of the normal Linq to SQL table methods (i.e. InsertOnSubmit, etc...) on the resolved object.

To get this framework setup and working there's quite a few things you need to build, but it's quite a fun exercise. Included in the source is a custom DataContext called XDataContext which turns the data store into XML files instead of database tables and still uses the Linq to SQL entities that are generated. You can simply just map the IDataContext to any custom data context using the Unity (Microsoft's dependency injection framework) configuration. I've also implemented PolicyInjection into this framework as it is extremely easy to do now that all of the objects are interfaced already. Now it's too easy to cache and log calls to methods.

There's a complete description of everything in the article.

Posted on 2/20/2009 1:28:00 PM by Shannon Deminick

Permalink | Comments (0) | Post RSSRSS comment feed |

Categories: Technology

Tags: , , , ,

 

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Copyright © 2010 TheFARM