简体   繁体   中英

Using dependency injection with ORM codr

I am trying to design a way to use dependency injection with ORM tools so that it will be easy to replace them if needeed. The problem is that it seems impossimble to separate orm code from the program. Even if I am able to separate functionality like save, fetch etc. I cannot replace entity instances floating around.

I wondering if what I am trying yo achieve is reasonable. If so what are some good approaches to achieve this ?

You'll have a dependency on some level/layer of your app no matter what you do. I mean, as soon as you introduce 3rd party code, it needs to be connected to your app somewhere.

You could go with a repository pattern and create a repository project in your solution and keep all the LLBLGen-related code in there. You would do all your DB interaction through it and you would have to pass some DTO-style objects to and from it to avoid leakage. You would also have to do all the mapping between LLBLGen and your DTO's in the repository.

So, if we're talking about a webapp, you could have something like WebAPI <-> Business Layer <-> Repository Layer <-> ORM

Also, in reality it's highly unlikely that you're going decide to swap out the ORM for a different one (and especially LLBLGen because it's a really good ORM) so you're perhaps slightly overthinking this bit. You should pick an ORM wisely up front and stick with it. If you already know you want to swap it out later, why not do it right away? And you typically wouldn't be using DI with something like LLBLGen entity objects anyway (not saying you couldn't). It's kind of like saying that you would like to use DI for DateTime in case you decide to instead use Noda Time to handle dates. The main point of DI is to make your code testable, and even with say having LLBLGen entities in your Business layer, that's wouldn't be an issue, you would still be able to mock repo methods and test the business layer nicely.

Some clarifications:
DTO = Data Transfer Objects
DI = Dependency Injection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM