Dependency Injection with Entity Framework - Connection Strings - entity-framework

Im currently creating a middle tier layer for editing rules for an application. The data access is handled using entity framework and a repository class. My manager has suggested to inject the connection string for the database down to the repository class and I'm confused as to his thinking behind this?
Is there any need for this and what benefits would it provide?
Thanks

Dependency injection gives you freedom of changing the string when for example unit testing. In your case, I believe you would be better of mocking the database instead, but if you have a test database that is to be used instead of a mock, that lets you change a connection string when instanciating the object.

Related

Persistence ignorance and DDD reality

I'm trying to implement fully valid persistence ignorance with little effort. I have many questions though:
The simplest option
It's really straightforward - is it okay to have Entities annotated with Spring Data annotations just like in SOA (but make them really do the logic)? What are the consequences other than having to use persistance annotation in the Entities, which doesn't really follow PI principle? I mean is it really the case with Spring Data - it provides nice repositories which do what repositories in DDD should do. The problem is with Entities themself then...
The harder option
In order to make an Entity unaware of where the data it operates on came from it is natural to inject that data as an interface through constructor. Another advantage is that we always could perform lazy loading - which we have by default in Neo4j graph database for instance. The drawback is that Aggregates (which compose of Entities) will be totally aware of all data even if they don't use them - possibly it could led to debugging difficulties as data is totally exposed (DAO's would be hierarchical just like Aggregates). This would also force us to use some adapters for the repositories as they doesn't store real Entities anymore... And any translation is ugly... Another thing is that we cannot instantiate an Entity without such DAO - though there could be in-memory implementations in domain... again, more layers. Some say that injecting DAOs does break PI too.
The hardest option
The Entity could be wrapped around a lazy-loader which decides where data should come from. It could be both in-memory and in-database, and it could handle any operations which need transactions and so on. Complex layer though, but might be generic to some extent perhaps...? Have a read about it here
Do you know any other solution? Or maybe I'm missing something in mentioned ones. Please share your thoughts!
I achieve persistence ignorance (almost) for free, as a side effect of proper domain modeling.
In particular:
if you correctly define each context's boundary, you will obtain small entities without any need for lazy loading (that, actually becomes an antipattern/code smell in a DDD project)
if you can't simply use SQL into your repository, map a set of DTO to your db schema, and use them into factories to initialize entity classes.
In DDD projects, persistence ignorance is relevant for the domain model itself, not for repositories, factories and other applicative code. Indeed you are very unlikely to change the ORM and/or the DB in the future.
The only (but very strong) rational behind persistence ignorance of the domain model is separation of concerns: in the domain model you should express business invariants only! Persistence is an infrastructural concern!
For example without persistence ignorance (and with lazy loading) the domain model should handle possible exceptions from the db, it's complexity grows and business rules are buried under technological details.
Personally I find it near impossible to achieve a clean domain model when trying to use the same entities as the ORM.
My solution is to model my domain entities as I see fit and ensure that any ORM entities don't leak outside of the repositories. This means that my repositories accept and return domain entities.
This means you lose "most of your ORM goodness" and end up "using your ORM for simple CRUD operations".
Both of these trade-offs are fine for me, I would rather have a clean domain model that I can use, rather than one polluted with artefacts from my DB or ORM. It also cuts down the amount of time I spend "wrestling with my ORM" to zero.
As a side-note, I find document databases a much better fit for DDD.
Once you will provide persistence mapping in you domain model:
your code depends on framework. If you decided to change this framework, you want to change persistence layer and model layer source code - more work, more changes, more merging of code etc.
your domain model jar file depends on spring/nhibernate jars etc.
your classes become larger and larger how business code and persistence related code grows
I've to admit that I dont understand harder and hardest option.
We used separated interfaces and implementations for domain entities. Provide separated mapping files using Hibernate along with repositories.
Entities are created using factory (or repository later), identifier is generated within persistence layer, entity does not need it until it's being persisted.
Lazy loading is provided by special implementation of List once:
mapping of an entity contains it
entity/aggregate is fetched from persistence layer
The only issue is related to transaction as when you use lazy-loaded collection out of transaction scope, it fails.
I would follow the simplest option unless I ran into a stone wall. There are also pitfalls such as this when you adopt pi principle.
Somtimes some compromises are acceptable.
public class Order {
private String status;//my orm does not support enum
public Status status() {
return Status.of(this.status);
}
public is(Status status) {
return status() == status;//use status() instead of getStatus() in domain model
}
}

Entity Framework - No Repository abstraction

In my project, I need to use EF and abstract the queries from the Presentation layer. Based from what I've been reading questions and answers all over the net, EF is built having repository pattern on it's DbSet and Unit of work on DbContext.
Repository pattern can easily do the requirement but I don't wanna repeat this implementation and now confused where should I initialize or access the DbContext. Should it be on the service layer?
MVC4 Api will be used for this project
One way I have seen this done in the past is to essentially remove the DbContext's dependency on a physical database by creating an interface for your context then make your data access calls from your Services Layer (Business Logic Layer).
There is however, a disadvantage in using this approach, which is the fact that your unit tests (which will be using a Fake implementation of your DbContext) will be using LINQ to Objects to run your queries whereas your concrete implementation will use LINQ to Entities which does not support all LINQ to Objects methods.
There's documentation on MSDN (http://msdn.microsoft.com/en-us/library/bb738550.aspx) which highlights these differences.
I also recommend reading this article (http://kearon.blogspot.com.au/2011/02/mocking-entity-framework-4-code-first.html) which demonstrates how to make DbContext unit testable by removing the inderlying dependency on a phyiscal database.
Hope this all helps!

How to define the EF connection string only once and re-use it in other projects?

I am building a web application that makes use of Entity Framework. I have moved the Entity Model and generated classes to a separate project, because it will be used by more than one consumer.
But when I try to run the application, Entity Framework tells me that
No connection string named 'X' could be ofund in the application config file.
To remove this problem, I would have to add the Entity Framework connection string to every consuming project. Of course this is annoying, because there are several consumers, and also it introduces a tight coupling that i hoped to get rid by dividing the software into different projects.
So is it possible to define the connection string in only one place and not in every consuming project?
NOTE: I am following the Database First approach.
This is possible, because you can instantiate a context with a constructor that accepts a connection string. In one of our projects we have a ContextFactory where the connection string is registered once at startup. All code in the assembly gets contexts from the factory.
Actually, in our case we use an ObjectContext, and create the connection string for the factory from the connection that is registered and the metadata string that was created when creating the context. We do this by using an EntityConnectionStringBuilder.

How can I configure multiple UnitOfWork classes for multiple databases?

I'm using Entity Framework (code first), Repositories, and the Unit of Work pattern, essentially as described here:
Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable
I'm also using StructureMap to manage my object instances and I have some code like this wiring up the EF dbcontext and unit of work:
For<DbContext>().HybridHttpOrThreadLocalScoped().Use<MyDbContext>();
For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<UnitOfWork>();
I also have a generic Repository<T> that currently knows about the MyDbContext instance. Now I need to be able to support multiple databases, and thus multiple DbContexts. I'm considering trying to adjust my IUnitOfWork to be instead an IUnitOfWork<T>, where T is the DbContext to use. But my repository will also need to know which DbContext to use, so do I then have to make it doubly generic (e.g. Repository<TEntity,TDbContext>)?
What's the best, simplest way to support multiple databases using the UnitOfWork pattern I'm using?
It depends on your application logic. Are you going to do changes in multiple databases withing single unit of work? If yes you should still use one unit of work with database factory for each database accessed within that unit of work. Commit of that unit of work should use TransactionScope to make changes in all database atomically (this can be little bit more challenging).
If you always need to make changes only in a single database you can use single generic unit of work but you also have to implement generic Get on database factory. Passing context type to the repository is not needed. Move the initialization logic to concrete repositories which know the type of context they must use and they will ask database factory for that context.

EF4 - possible to mock ObjectContext for unit testing?

Can it be done without using TypeMock Islolator? I've found a few suggestions online such as passing in a metadata only connection string, however nothing I've come across besides TypeMock seems to truly allow for a mock ObjectContext that can be injected into services for unit testing. Do I plunk down the $$ for TypeMock, or are there alternatives? Has nobody managed to create anything comparable to TypeMock that is open source?
I'm unit testing EF4 easily without mocking. What I did was create a repository interface using the code from http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/ as a basis I then created an InMemoryRepository<T> class that used the IRepository interface. I then replaced the IObjectSet<T> with a List<T> inside of the class and changed the retrieval methods accordingly.
Thus if you need to do unit testing, pass in the InMemoryRepository rather than the DataRepository.
Put your Linq2Entity query behind an interface, unit test it in isolation against a real database.
Write tests for your business logic with mocks for your query interfaces. Don't let Linq bleed into your business logic!
Don't use the RepositoryPattern!
Wrap the ObjectContext in a proxy class. Then inject that into your classes.
I don't think the repository pattern is the only answer to the question (it avoids the problem, sure)
I liked this answer - I think more appropriate for introducing tests to an existing codebase Creating Interface for ObjectContext