Sql – How to sort this Repository pattern and ASP.Net website architecture

Architectureasp.netdesign-patternslinq-to-entitieslinq-to-sql

I am Creating a new ASP.Net website "not mvc", and willing to make the data access layer has 2 versions, one using the Linq to Sql and another one using ad.net entity framework.
Note: kigg is doing the same but in MVC website and too complex than i want.
I learned that the best pattern to achieve my goal is using repository design pattern.

My question is, where in my code and layers "dal, bal, ui" the switch will happen? in other words where i will change the code to apply the linq to sql to ado.net entity framework or vice versa.

I wrote:

IRepository repository;

Then in the class constuctor

repository = MyRepositoryLinqToSql();

can some one teach me this part architecture wise?

Best Answer

If you want to create a pluggable architecture to be able to swap out the repository layer on the fly then you will need to create everything behind an interface and then use something like StructureMap to dynamically swap in what you need when you need it.

You would want to define a repository class like AccountRepository. One for linq to sql LSAccountRepository and EFAccountRepository. Both of these would inherit from IAccountRepository and have methods such as GetAccountByID, SaveAccount, DeleteAccount, etc.

Then using StructureMap you would have syntax like so to load the appropriate repository based on the system that you are loading in.

IAccountRepository _accountRepository = ObjectFactory.GetInstance();

Then via your configuration you can specify the default implementation of IAccountRepository and swap this out to point to either implementation at any time.

If this is too complex then a dependancy injection patten can be used in that you can have a method with a parameter of IAccountRepository. This method would be called by a controller (MVP or MVC) and you can pass in the appropriate reference at that time. This way you do not directly instantiate the repository inside of the method that might need one repository vs. another.

Even if you do decide to do a DI pattern you can still use StructureMap. When you instantiate an object that has other dependancies in it that StructureMap knows about (in the constructor) then StructureMap will also load up those objects as well. Then the caller of the object that has the method that you need will be the only loose coupling that is needed as StructureMap will dynamically take care of the dirty work for you.