Setting EF to work with Castle Windsor - entity-framework

I have set up my project to work with Entity Framework. It is a database first approach.
For the IoC, I am using Castle Windsor and the project is set up to inject all the dependencies.
My question is, is there a need to set up Castle to do the same for my EF entity? How can I do that?

There are a number of ways to use Entity Framework with Castle. I would suggest that you adopt both the Unit of Work and Repository patterns. The DbContext provides most of the functionality for a unit of work, and DbSet similarly provides most of what is needed for a repository.
The main issue you will run into is that EF doesn't understand dependency injection for model objects. EF always uses the empty constructor when it allocates a model object, and this means we don't get the opportunity to do dependency injection into model objects. We have gotten around this by using the object materialization hook on the DbContext:
((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += EFObjectLoadInitializer;
The EFObjectLoadInitializer then injects the Kernel into the model object (all our model objects must support the IInjectKernel interface). Upon injection, the Kernel is then used to resolve any other dependencies. Its not very clean, but it works well and allows us to leverage off of the rest of the infrastructure that we have set up with Windsor.

Related

Entity Framework object materialization and dependency injection

I would like to be able to inject some dependencies (by using an IoC container) into entities just after they are loaded and materialized by Entity Framework (as a result of a query for instance).
It is possible to do so by hooking on the ObjectMaterialized event but I'm wondering if there is no better manner to achieve this as I use EF 6 and code first.
Any advices or ideas ?
Thanks
Riana
Although Entity Framework can be configured to allow dependencies to be injected into entities, I think it's safe to say that the general consensus (take a look at the opinions of Jimmy Bogard, Mark Seemann and me) is to not do this at all.
For me the main point is that classes like entities, DTOs and messages are very different from service classes. Entities, DTOs and messages are short lived objects containing runtime data, while services contain behavior, are often long lives and simply process runtime data (such as entities).
That doesn't mean that you can't use services into your entities though. As Mark describes here, not letting your entities use services lead to an Anemic Domain Model. But what this means is that entities shouldn't be part of your object graph.
Instead, if you are practicing DDD, your entities can simply accept dependencies into the domain methods that you define on the entities. Those dependencies can than be supplied by the command handlers that execute the use case. In other words, dependencies are injected into the constructor of a command handler, and when calling an entity's domain method, the command handler will supply the dependencies that this method requires (usually just one or two) to that method (method injection).

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 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.

Which variant of Entity Framework to use in WCF based enterprise app

We are in a process of designing an application with approx 100 tables and complicated business logic. Windows Forms will be used on the client side and WCF services with MSSQL on the server.
Custom DTOs are used for client-server communication, business entities are not distributed.
Which variant of Entity Framework to use (and why):
EF 4.0 EntityObjects
EF 4.0 POCO
EF 4.1 DbContext
Something else
Database-first approach is a requirement.
Also, is it worth implementing a Repository pattern? It seems a bit redundant, as there is one level of abstraction in the mapping itself and another one in the use of DTOs. I'm currently leaned towards using auto-generated extendable repositories for each entity returning IQueryable, just to have a place to put common queries, but still allowing querying entity model directly from the Service Layer.
Which variant to use? Basically once you have custom DTO the only question is do you want to have control over entities code (their base class) and make them independent on EF? Do you want to use code first? If the answers to all questions are no then you can use EntityObjects. If you want to have entities persistence ignorant or use custom base class you should go to POCO. If you want to use code first or new DbContext API you will need EF 4.1. Some related topics:
EF 4.1 Code-first vs Model/Database-first
EF POCO code only VS EF POCO with Entity Data Model (this was related to CTP)
ADO.NET DbContext Generator vs. ADO.NET POCO Entity Generator
EF Model First or Code First Approach?
There are more things to consider when designing service layer. You should be aware of complications you will have to deal with when using EF in WCF. Your service will provide data to WinForms application and it will work with them in "detached mode". Once user will do all changes he wants to do he will post data back to the service. But here comes the problem - you must tell EF what has changed. If you for example allow user to change order with all its order items (change quantity in items, add new items, delete some items) you must say EF exactly what has changed, what was added and what was deleted. That is easy when you work with single entity but once you allow user to change object graph (especially many-to-many relations) then it is quite tough. The most common solution is loading the whole graph and merge the state from incoming DTOs to loaded and attached graph. Other solution is using Self tracking entities instead of EntityObjects/POCOs + DTOs.
When discussing repositories I would refer you to this answer which refers many other answers discussing repositories, their possible redundancy and possible mistakes when using them just to make your code testable. Generally each layer should be added only if there is real need for the layer - due to better separation of concerns.
The main advantage of POCOs is that those classes can be your DTOs, so if you've already got custom DTOs that you're using, POCO seems a bit redundant. However, there are some other advantages which may or may not have value to you, since you didn't mention unit testing as a requirement. If you plan to write unit tests, then POCO is still the way to go. You probably won't notice much difference between 4.0 POCO and 4.1 since you won't be using the code-first feature (disclaimer: I've only used 4.0 POCO, so I'm not intimately familiar with any minor differences between the two, but they seem to be more or less the same--basically I was already using POCO in 4.0 and haven't seen anything that's made me want to update everything to use 4.1).
Also, depending on whether you plan to unit-test this layer, there's still value in implementing the repository/unit of work patterns when using Entity Framework. It serves to abstract away the data access logic (the context), not the entities themselves, and allows you to do things like mocking your context in unit tests. What I do is copy the T4 template for my context and use it to create the interface, then edit the T4 template for the context and have it implement that interface and use IObjectSet<T> instead of ObjectSet<T>. So instead of:
public class MyEntitiesContext
{
public ObjectSet<MyClass> MyEntities
...
}
I end up with:
public interface IMyEntitiesContext
{
public IObjectSet<MyClass> MyEntities;
}
and
public class MyEntitiesContext : IMyEntitiesContext
{
public IObjectSet<MyClass> MyEntities
...
}
So I guess it really comes down to whether or not you plan to write unit tests for this layer. If you won't be doing anything that would require mocking out your context for testing, then the easiest thing to use would probably be 4.0 EntityObjects, since you aren't planning to pass your entities between layers and it would require the least effort to implement. If you plan to use mocking, then you'll probably want to use POCO and implement repository/unit of work.

GWT + entities + JPA + DTO + Dozer

I am wondering what is the best way to handle mapping of entity beans (JPA 2) to DTOs.
Since you cannot use entity beans "directly" with GWT, you need to handle DTOs instead.
I have several entities with various relationships (OneToOne, OneToMany, ManyToMany with a join table etc).
Initially i started converting all entities to DTOs by hand with the help of a class MyEntityTransform.java with methods like :
static final public CarBean persistant2Bean(CarPersist) {
return new CarBean(cartPersist.getId(), carPersist.getName(),
carPersist.getDescription());
}
Other methods are : persistent2BeanCollection(...), persistent2BeanMap(...), bean2Persistent(...), bean2PersistentCollection(...)
That becomes a fastidious task when handling collections, especially when the same entity has references to several other entities;
I have been thinking about using the DOZER framework to handle the mapping between entities and DTOs.
It is mentionned here : http://code.google.com/intl/fr/webtoolkit/articles/using_gwt_with_hibernate.html
However i am not sure how well it handles the various JPA mappings (manytomany for instance) and how much work it is to configure it in the dozer-bean-mappings.xml file.
Also i guess this framework is intensively using reflection to perform mapping operations. Such approach is much slower than mapping performed "by hands", e.g. when i use the methods in my MyEntityTransform.java class.
What do you suggest ? i'm interested in everybody's experience handling JPA entities with GWT.
Thanks.
Celinio
http://www.celinio.net/techblog
In first instance I would always prefer Dozer. When the DTO structure is the same as your entities, you can use Dozer with zero configuration by simply calling the map function. When your DTOs differ from your entities the configuration overhead is minimal. Simply look in the really good documentation.
When performance becomes an issue, I would prefer a code generator approach, but I would never write the mapping code by myself cause it can be very error prone.
If you want to just include entities in you EJB or JPA module in your GWT module follow these steps. I found it out my own and It worked for me.
Include your EJB module in GWT module's build path (you may have already done that)
Now goto your entities package in EJB module (i will take it as "com.ejbproject.entities")
Create a file named Entities.gwt.xml (<ProjectSourcePath>/com/ejbproject/entities/Entities.gwt.xml)
File content should be
<module>
<source>com.ejbproject.entities</source>
</module>
Now include following fragment in your GWT project's <modulename>.gwt.xml file.
<inherits name="com.ejbproject.entities.Entities"/>
Now you can include Entities in your GWT client side and gwtCompile without any problem