How does avoiding anaemic domain models work with ORMs, Dependency Injection and a Solid approach - entity-framework

having looked at Domain Driven Design and read about Anaemic Domain Models being an antipattern, thinking ok perhaps should put more behaviour into our domain entities. The Behaviour will need handling for flexibility using SOLID approach, hence the need for a DI framework and container to allow injecting some behaviours into the entities.
However there appears a mismatch in wiring up the Entities, as our Entities would coming from an ORM framework such as Entity Framework or NHibernate, and Behaviours coming from a Dependency Injection container.
I guess you need a way for the ORM to also have a DI Container plugged into it.
Just wondering how others have approached this when wanting to get more rich models but also use ORMs and DI containers.

1- It is not a good idea to use ORM entities as your domain entities. Because your domain entities constitute the core of your DDD application and should have the minimum dependencies. What if you decide to change your ORM in the future? ORM can be used in your Repositories but remember that you need to map the ORM entities to your domain entities before your repository returns them.
2- Your domain entities should have behaviors but they are limited to that entity only. Any behaviors that involve other services or dependencies should go to a domain service. So your domain entities wouldn't have dependency on other services. They usually don't even need abstraction, so they won't need to be resolved using an IoC container.

I came upon one potential answer after watching this excellent video by Jimmy Bogard on Crafting Wicked Domain Models.
So your domain model contains the behaviour and rich methods, but you inject into the method of the domain model specific behaviours which implement some interface and are bits of functionality that you can get out of a DI container.
So by altering what you inject into the model, we can alter its behaviour using DI whilst still having a rich domain model and retrieving it from the database via an ORM.

Related

Entity Framework 6 Database-First and Onion Architecture

I am using Entity Framework 6 database-first. I am converting the project to implement the onion architecture to move towards better separation of concerns. I have read many articles and watched many videos but having some issues deciding on my solution structure.
I have 4 projects: Core, Infrastructure, Web & Tests.
From what I've learned, the .edmx file should be placed under my "Infrastructure" folder. However, I have also read about using the Repository and Unit of Work patterns to assist with EF decoupling and using Dependency Injection.
With this being said:
Will I have to create Repository Interfaces under CORE for ALL entities in my model? If so, how would one maintain this on a huge database? I have looked into automapper but found issues with it presenting IEnumererables vs. IQueryables but there is an extension available it has to hlep with this. I can try this route deeper but want to hear back first.
As an alternative, should I leave my edmx in Infrastructure and move the .tt T4 files for my entities to CORE? Does this present any tight coupling or a good solution?
Would a generic Repository interface work well with the suggestion you provide? Or maybe EF6 already resolves the Repository and UoW patterns issue?
Thank you for looking at my question and please present any alternative responses as well.
I found a similar post here that was not answered:
EF6 and Onion architecture - database first and without Repository pattern
Database first doesn't completely rule out Onion architecture (aka Ports and Adapters or Hexagonal Architecture, so you if you see references to those they're the same thing), but it's certainly more difficult. Onion Architecture and the separation of concerns it allows fit very nicely with a domain-driven design (I think you mentioned on twitter you'd already seen some of my videos on this subject on Pluralsight).
You should definitely avoid putting the EDMX in the Core or Web projects - Infrastructure is the right location for that. At that point, with database-first, you're going to have EF entities in Infrastructure. You want your business objects/domain entities to live in Core, though. At that point you basically have two options if you want to continue down this path:
1) Switch from database first to code first (perhaps using a tool) so that you can have POCO entities in Core.
2) Map back and forth between your Infrastructure entities and your Core objects, perhaps using something like AutoMapper. Before EF supported POCO entities this was the approach I followed when using it, and I would write repositories that only dealt with Core objects but internally would map to EF-specific entities.
As to your questions about Repositories and Units of Work, there's been a lot written about this already, on SO and elsewhere. You can certainly use a generic repository implementation to allow for easy CRUD access to a large set of entities, and it sounds like that may be a quick way for you to move forward in your scenario. However, my general recommendation is to avoid generic repositories as your go-to means of accessing your business objects, and instead use Aggregates (see DDD or my DDD course w/Julie Lerman on Pluralsight) with one concrete repository per Aggregate Root. You can separate out complex business entities from CRUD operations, too, and only follow the Aggregate approach where it is warranted. The benefit you get from this approach is that you're constraining how the objects are accessed, and getting similar benefits to a Facade over your (large) set of database entities.
Don't feel like you can only have one dbcontext per application. It sounds like you are evolving this design over time, not starting with a green field application. To that end, you could keep your .edmx file and perhaps a generic repository for CRUD purposes, but then create a new code first dbcontext for a specific set of operations that warrant POCO entities, separation of concerns, increased testability, etc. Over time, you can shift the bulk of the essential code to use this, while still keeping the existing dbcontext so you don't lose and current functionality.
I am using entity framework 6.1 in my DDD project. Code first works out very well if you want to do Onion Architecture.
In my project we have completely isolated Repository from the Domain Model. Application Service is what uses repository to load aggregates from and persist aggregates to the database. Hence, there is no repository interfaces in the domain (core).
Second option of using T4 to generate POCO in a separate assembly is a good idea. Please remember that your domain model (core) should be persistence-ignorant.
While generic repository are good for enforcing aggregate-level operations, I prefer using specific repository more, simply because not every Aggregate is going to need all of those generic repository operations.
http://codingcraft.wordpress.com/

Non business logic database access in DDD

just starting with DDD. I understand that all the domain entities and their logic should be kept in Domain layer along with repository interfaces. In my application I store some data in the database that is used to construct parts of the user interface (presentation layer) at run time. Where should I keep the poco classes and repository interfaces for such types, in Application layer or Domain layer. I can not make out because these objects will not have any domain related business logic but they need to be hydrated from the database and I am using EF so for data access I will need entities and repositories so to me obvious choice is to keep them with all other entities and repository interfaces in domain layer but that breaks DDD rules
I think you've answered your own question:
In my application I store some data in the database that is used to
construct parts of the user interface (presentation layer) at run
time.
Access to data that is used to serve the UI should be encapsulated in the presentation layer. This is different from the application layer in that a DDD application layer implements use cases by orchestrating repositories and delegating to appropriate entities, domain services - it forms an API around your domain layer. Different presentation implementations can use the same application service.
However, different presentation layer implementations may require different data. Therefore, place presentation data access directly in the presentation layer. This can be implemented with EF which is not exclusive for DDD scenarios.
A good way to think of it is this - if you had to replace EF with stored procedures for performance reasons, you should not have to modify your domain code. So anything that blocks that needs to be hidden behind an interface and made replaceable.
Repositories CAN be a part of domain logic. However what should not be is the mechanism for persistence. This can easily be encapsulated into a DAL service or other object, which of course is programmed to an IDALService interface. So when you need to switch persistance (for example, moving from EF to a NoSQL solution) you simply write an alternative version that implements the IDALService interface, and you're good to go. The repositories can still do the logic within them, but are now using a new way to store them (this is an Inversion of Control idea).
As for the POCO objects, in DDD the real question is what do they represent? Are they entities, that need to be persisted? Are they value objects? Don't let the technology (EF) determine what the structure of your object model is, instead provide means to translate to an application scope.
In the Application layer. Keep the domain intact and isolated.

How to utilize domain driven development in asp.net mvc4 effectively?

I want to start new application on ASP.NET MVC4 using different different approach like domain driven development , design patterns , dependency injection , Entity Framework as ORM etc.
Need some advice on what should be the starting point of development? Should I start with first relationships of classes or start with traditional approach?
e.g there are three module.
User Management.
Logging.
Error Logging.
Should I first complete with user management like domain classes then its services and then its CRUD operations in actual web application? and after that ...will start with logging (same process as mention in user management). and then in error logging as well.
So What are best practices to start development using those kind of concept or tools?
ASP.NET MVC4 is just a presentation part of solution. With Domain-Driven approach you start with domain (usually separate library project) and then add presentation (web site, desktop application etc) and persistence (implementation of repository and uof interfaces declared in your domain).
So, you start with creating domain model (not whole, but part of that). Then in any order you create UI which uses you domain model, and implementation of repositories for persisting your domain model via Entity Framework. Well actually views should use ViewModels (otherwise your POCO domain objects will be polluted with Data Annotations attributes and other stuff). It's a controller part where you will use domain model. Also you will inject repository implementations to controllers via dependency injection.
I would start by looking at the business functionality requirements of the system and focus on the highest value requirements first. Implement those, filling out your business domain as you need to, based on delivering the requirements. If you follow a BDD style process, you can use unit tests to drive out the business functionality and your domain will evolve as the business requirements evolve. Each business requirement should have a UI and data access component to it so you can fill out the presentation layer and data access layer with Entity Framework as the domain evolves. Here's a couple of useful posts on BDD:
BDD By Example
Introducing BDD

Considering the following architectural changes and need some advice (Domain Entities, DTO, Aggregates)

about a year ago I set set up a solution consisting of an ASP.Net MVC 3 (now) presentation layer, application layer, domain layer and infrastructure layer (crosscutting stuff and data). I decided to keep the domain model in a separate project from the domain logic and use a relaxed approach to the presentation layer by passing the domain entities instead of DTO's since we really only have 1 front end right now.
We are going to be servicing a distributed layer soon, in addition to our main website and I will use DTO's there, but I am considering using DTO's in the main website also. I am also wondering if I should bother to break out the framework code in the domain layer (IRepository, IUnitOfWork, Entity/Value object supertypes etc). Well here, let me list out the questions I need feedback on:
1) I was pretty diligent about not having an anemic domain model and also watched out for behavior that was specific to the presentation concerns. Most of the business calculations that are needed are on the domain entities, is it ok for the presentation layer to call this behavior directly or should it instead call an application service that then calls the domain entities? This would suggest to me that there is no reason to have the presentation layer know about the domain entities and instead could use DTO's. Alternatively, I could have the DTO's expose these behaviors, but then I feel like I am robbing the domain entities. So I guess that is 3 options (Rich domain objects called directly, service layer or dto with behavior) which is best?
2) Right now I have a domain project, which has domain services, specifications and logic and is orchestrated by the application layer and separate project for the domain model (used by presentation layer and application layer). I also have framework interfaces for generic repository and unit of work pattern here. Should I break the framework stuff out into a separate project and combine the rest into one project?
3) I want to reorganize my domain layer into aggregates, right now all of the domain model is organized by modules, basically all the types for each module are in one namespace. Would it be better to organize the entities, value objects, services and other stuff by the aggregates?
4) Should I use the Separated Interface pattern for infrastructure services that are basically .net framework helper library types? For example configuration objects or validation runners? What is the benefit there in doing so?
5) Lastly, not many examples I have seen have used interfaces for domain entities. Almost every object I have I prefer to pass around interfaces for dependency reasons and it makes testing much easier. Is it valid to use interfaces instead of concretes? I should mention that we use EF 4.3.1 (soon to upgrade to latest version) and I seem to remember that EF had a problem with using interfaces or something. Should I be exposing interfaces instead of the domain entities?
Thank you very much in advance.
Project Structure:
Presentation.Web
| |
| Application
| | |
Domain.Model - Domain
(Infrastructure.Data, Infrastructure.Core, Infrastructure.Security)
Explanation:
Presentation.Web (MVC3 Web Project)
Application
-- Service Layer that orchestrates the domain layer and responds to requests from the presentation layer (get this update that). This is organized by module, for example if I had a customer module I would have Application.Customer and in that would be all of the application services
Domain
-- Contains domain services, specifications, calculations and other domain logic that is not exposed as behavior on domain entities. For example a calculation that involves several domain entities exposed as a domain service for the application layer to call.
-- Also contains framework code for a specification framework and the main interfaces for a generic repository and unit of work pattern.
Domain.Model
-- Contains the domain entities and enumerations. Organized by module. For example, if I might have a customer module which has a customer entity, customerorder entity etc. This is broken out away from the domain project so that the objects can be used by the application and presenation layer.
Infrastructure.Security
-- Security infrastructure for authentication and authorization
Infrastructure.Core
-- Cross-cutting stuff used by multiple layers (validators, logging, configuration, extensions, IoC, email etc..). Most of the projects depend on interfaces in this project (except domain.model) for infrastructure services.
Infrastructure.Data
-- Repository Implementations via LINQ and EF 4.3.1, mapping layer, Unit of Work implementation. Interfaces are in Domain project (separated interfaces pattern)
1) First, determine whether your main website really needs to use the application layer. IMHO, if your application services and your main website are on the same web server, then you should evaluate whether the potential performance loss is worth having your main website call app server methods when it could call the domain objects directly. However, if your application server is definitely on another server, then yes, you should have the application server call your domain objects and pass only DTOs back and forth between it and any presentation layers you may have, including your main website.
2) This is really a question on preference of organization. Both are valid. You choose.
3) Anoter question on preference of organization. I, personally, organize my code by bounded context first. Then, I have entities and aggregate roots directly under them. Then, I have folders for Enumerations, Repositories (interfaces), Services (interfaces), Specifications, and Values. The namespaces do not reflect this organizational structure past the last bounded context folder. But, again, you should do this in the way that best suits the way you look at the code.
4) This is an implementation concern. I, personally, only break out implementation concerns into interfaces if I think there is a good possibility that I will need to swap out the implementations in the future. That being said, I usually organize my helper libraries into specific infrastructure contexts (eg. MainContext.Web.MVC.Helpers or MainContext.Web.WebForms.Helpers.) These rarely change and I have yet to come across an instance where I needed to swap out implementations entirely.
5) From my understanding, it is perfectly valid to use interfaces instead of concretes for your domain entities. That being said, I have yet to run into a case where I needed different implementations for my domain entities. The only reason I can even think of would be if you needed to change your business logic for one application, but leave an older application using the original business logic. If your business objects are good models for the domain, I can't fathom you actually running into this problem, but I have seen examples where people do this just for the sake of the abstraction. IMHO, that is not worth the extra coding effort, but if it makes you feel good inside or you get some actual benefit (eg. making testing easier), there isn't any reason why you can't abstract out your domain entities. That being said, domain services and repositories should definitely have contracts that allows you to swap out their implementations.
Answer 5 is derived from the idea that the application is the one who chooses the implementations. If you are trying to achieve onion architecture, then your application is going to be choosing the concrete implementations for everything (repositories, domain services, and other abstracted implementation concerns). I see no reason why it can't just use domain aggregates directly since they are the concrete representation of your domain model. (Note: All entities should be encapsulated into aggregates. The application should never be able to hold a reference to an entity that is not an aggregate under the context)

Where "ADO.NET Entity Framework" files in 3 layer architecture?

If I use ADO.NET Entity Framework in our project and we depend on a 3-layer architecture pattern that we have ( presentation layer - business layer - data access layer ) a project for each layer.
So when I make an entity model file where can I put it in the DAL or BL? If I put it in the DAL and from the presentation layer want to access a domain object in it through the business layer so we need to add a reference to the DAL in the presentation layer. Also, how do I get that type of an object as it is created in the DAL? On the other hand should I put the entity model file in the business layer? Which is the better and why?
Ideally, the EntityFramework generated code makes up your data layer. You would basically have some repetition then in your business layer if you needed the same sorts of objects in your business layer as you have in your data layer. Unfortunately, EntityFramework doesn't really help you at all with your business layer.
Now, you'll also read things about EntityFramework that say you can/should use it as a combined data/business layer. That violates Separation of Concerns, so I would guide you away from it, but I'm sure a ton of people do it anyway. If you wanted to move from EntityFramework to NHibernate some day, you'd be best off trying to isolate your ORM from the rest of your code base and minimize any coupling to the ORM (often through implementing something like a Repository pattern).
People who talk the language of MVC will often use EntityFramework as the Model and may or may not distinguish between a data layer and a business layer (which generally would both live in the Model). Even if you use MVC, I still believe you should decouple your data access from your business rules and business logic.
You can place the entities in a separate class library project, for example: Common Entity Library. This library can be referenced in any other app layers. You can then work with collections across application domain.
As I see it the Entity Framework is your DAL. It provides the needed tools to abstract the Model objects exposed by the Entity Framework from the persistance services of a backend database.
The Entity Framework straddles both the Business Layer and the DAL from this old three layer pattern. My advice is if you going with the Entity Framework is stop thinking in terms of Presentation->Business->Data and think more in terms of View->Model.