问题
We are using Entity Framework in a service library for my application but don't want to have a dependency on EF in any application which makes reference to this DLL. The problem we have is the main application has two problems:
- It doesn't have the references to EntityFramework.dll (I think this is an MSBuild issue?)
- I'm required to put the connection string in the main applications App.Config file
Are there any solutions for this or do we have to just accept any application using this DLL will require a NUGet install of EF?
回答1:
If your library needs access to the code in the Entity Framework, it will need the code of the Entity Framework, provided by EntityFramework.dll.
If another application makes use of your library, it will therefore also need the code in the EntityFramework dll. You can't run code you don't have. The (transitive) dependency is unavoidable.
回答2:
We are using Entity Framework in a service library for my application but don't want to have a dependency on EF in any application which makes reference to this DLL.
Then you need to split your library into classes that use EF and those that don't. If your library uses EF then the app will need to reference it, otherwise you will get a missing reference error at run-time.
I'm required to put the connection string in the main applications App.Config file
Yes, that's how application configuration works. You configure the application (including all dependent libraries) in app.config.
回答3:
Best case scenario you still need the connection string in your main config file. When you compile your project, your library dll gets copied over to the main bin folder. From then onward it will read the connection string details from the config file of your host application. Nothing you can do about that basically.
Now, if you want to not have a dependency on EF in your main project that is doable as well, but this means you cannot use any code which involves EF.
If you use a db first approach then EF will create model classes for your data. I prefer to not use those classes because they only exist in your EF context. You're better off using DTOs - Data Transfer Objects which live in a separate library for reuse purposes basically. Then you can swap from EF to something else easily should you need that. Keep in mind that this is not the main purpose, the main purpose is to achieve Separation of Concerns and not hardcode yourself into using any database layer.
So, use DTOs, make your library return data using those DTOs which means that your main app never needs to know anything about EF and you can drop the reference to it.
Here's an example of what I mean : https://eidand.com/2014/08/17/separation-of-concerns-application-layers/
来源:https://stackoverflow.com/questions/38375876/using-a-dll-which-in-turn-uses-entity-framework