Implementing localization in DDD pattern - Infrastructure/Persistance Layer? - asp.net-core

I'm working on a Blogging platform in .NET Core and one of the key requirements is to have different translations based on the user's selected language. It's clear to me that majority of this part belongs to the UI layer, but I want to let bloggers submit different translations of their posts by themselves.
So far I modified my Domain that it now contains the Language property and I also created Localized attribute to mark properties that are multilingual. In my approach I want to keep all localization-related logic in the Infrastructure layer so it saves/loads proper translations to/from another table containing translations for Localized properties automatically without the Application layer (or services) knowing about it.
I'm also implementing UnitOfWork pattern and normally I would use repositories through it, like in a following way: UnitOfWork.BlogPosts.Add(post) and after all operations are done: UnitOfWork.CommitChanges(), but I assume that now UnitOfWork would contain both repositories: for BlogPost and for Localization and the whole logic of saving/loading localized data would need to be implemented in a UnitOfWork so instead I would have to call a method that manages both repositories, like this: UnitOfWork.AddBlogPost(post) (also IUnitOfWork interface would require these methods).
So my question is: is it a good design appraoch and is UnitOfWork a proper place to implement such logic? I want to keep it as automated as possible and if it doesn't cause any issues that I'm currently not aware of - to keep it directly in a persistance layer.
Edit: My second idea would be to simply keep the two repositories in UnitOfWork and implement saving/loading BlogPost + Localization in an Application layer (in commands handlers and queries using CQRS pattern). But unfortunately this way I would have to implement the same logic for saving/loading for every command and query...

Related

How does the Repository Pattern Differ from a Simple Data Access Layer?

I've been confused by what I've been reading during my research on the repository pattern. I'm wondering if folks are (incorrectly?) using that word when they simply mean a data access layer.
Since "repository" is not found in the index of Design Patterns (GoF), I've turned to Patterns of Enterprise Application Architecture (Fowler). Fowler seems pretty clear (page 323) when he states that clients create a criteria object and pass it to the repository to get the results. It looks something like this:
public class Person
{
public List<Person> Dependents()
{
Repository repository = Registry.personRepository();
Criteria criteria = new Criteria();
criteria.equal(Person.BENEFACTOR, this);
return repository.matching(criteria);
}
}
Is the criteria object what makes the repository a repository? If not, what does? If abstracting the persistence mechanism (and therefore constructing queries) is the goal, in what way does the repository differ from a simpe DAL/ORM call like this:
public class PersonLogic
{
public List<Person> GetDependents()
{
IPersonData personData = DependencyContainer.Resolve<IPersonData>();
return personData.GetDependents();
}
}
To me, the difference looks like this:
* With the repository pattern, the client constructs different criteria objects and calls the Matching() method on it.
* With the simple DAL, clients just call different methods based on what they want.
Is there more to it than this? Are programmers mistakenly using the term "repository" when they really mean DAL?
EDIT
David Osborne sent this link to Persistence Patterns. It states:
Basically, the Repository pattern just means putting a façade over
your persistence system so that you can shield the rest of your
application code from having to know how persistence works.
That's really what a data access layer is. It really appears to me that a repository and a DAL are the same thing, and maybe a "true" repository uses the criteria object.
Take a look at the "Using the IQueryable interface" section and beyond at Extending and Enhancing the Orders and Registrations Bounded Context. It provides an insightful and balanced discussion of DAO/Repository implementations.
As subsequently highlighted by Bob Horn, the Persistence Patterns articles summarises that:
Basically, the Repository pattern just means putting a façade over your persistence system so that you can shield the rest of your application code from having to know how persistence works.
In general I agree with author's statements, but I'd like to add some details
Difference between Repository and DAL/ORM that first not only abstracts the persistence mechanism, but also provides collection-like interface for accessing domain objects … and isolates domain objects from details of the database access code:
Differences
For external layers, such as Business Logic:
Helps to avoid leaky abstraction. External layers depend on abstraction of Repository, rather than a specific implementation of DAL/ORM. Thus you could avoid all infrastructure and logical dependencies while working with Repository.
operates with domain objects, rather then a instances of POJO/POCO/DTO
CRUD operations applied to collection-like interface provided by Repository, rather then specific DAL/ORM methods. For example .net: working with collection that implements IEnumerable, rather then entity-framework context or nhibernate session
Similarities
Repository contains DAL/ORM underneath and serves same purpose

DDD: Where to put persistence logic, and when to use ORM mapping

We are taking a long, hard look at our (Java) web application patterns. In the past, we've suffered from an overly anaemic object model and overly procedural separation between controllers, services and DAOs, with simple value objects (basically just bags of data) travelling between them. We've used declarative (XML) managed ORM (Hibernate) for persistence. All entity management has taken place in DAOs.
In trying to move to a richer domain model, we find ourselves struggling with how best to design the persistence layer. I've spent a lot of time reading and thinking about Domain Driven Design patterns. However, I'd like some advice.
First, the things I'm more confident about:
We'll have "thin" controllers at the front that deal only with HTTP and HTML - processing forms, validation, UI logic.
We'll have a layer of stateless business logic services that implements common algorithms or logic, unaware of the UI, but very much aware of (and delegating to) the domain model.
We'll have a richer domain model which contains state, relationships, and logic inherent to the objects in that domain model.
The question comes around persistence. Previously, our services would be injected (via Spring) with DAOs, and would use DAO methods like find() and save() to perform persistence. However, a richer domain model would seem to imply that objects should know how to save and delete themselves, and perhaps that higher level services should know how to locate (query for) domain objects.
Here, a few questions and uncertainties arise:
Do we want to inject DAOs into domain objects, so that they can do "this.someDao.save(this)" in a save() method? This is a little awkward since domain objects are not singletons, so we'll need factories or post-construction setting of DAOs. When loading entities from a database, this gets messy. I know Spring AOP can be used for this, but I couldn't get it to work (using Play! framework, another line of experimentation) and it seems quite messy and magical.
Do we instead keep DAOs (repositories?) completely separate, on par with stateless business logic services? This can make some sense, but it means that if "save" or "delete" are inherent operations of a domain object, the domain object can't express those.
Do we just dispense with DAOs entirely and use JPA to let entities manage themselves.
Herein lies the next subtlety: It's quite convenient to map entities using JPA. The Play! framework gives us a nice entity base class, too, with operations like save() and delete(). However, this means that our domain model entities are quite closely tied to the database structure, and we are passing objects around with a large amount of persistence logic, perhaps all the way up to the view layer. If nothing else, this will make the domain model less re-usable in other contexts.
If we want to avoid this, then we'd need some kind of mapping DAO - either using simple JDBC (or at least Spring's JdbcTemplate), or using a parallel hierarchy of database entities and "business" entities, with DAOs forever copying information from one hierarchy to another.
What is the appropriate design choice here?
Martin
Your questions and doubts ring an interesting alarm here, I think you went a bit too far in your interpretation of a "rich domain model". Richness doesn't go as far as implying that persistence logic must be handled by the domain objects, in other words, no, they shouldn't know how to save and delete themselves (at least not explicitely, though Hibernate actually adds some persistence logic transparently). This is often referred to as persistence ignorance.
I suggest that you keep the existing DAO injection system (a nice thing to have for unit testing) and leave the persistence layer as is while trying to move some business logic to your entities where it's fit. A good starting point to do that is to identify Aggregates and establish your Aggregate Roots. They'll often contain more business logic than the other entities.
However, this is not to say domain objects should contain all logic (especially not logic needed by many other objects across the application, which often belongs in Services).
I am not a Java expert, but I use NHibernate in my .NET code so my experience should be directly translatable to the Java world.
When using ORM (like Hibernate you mentioned) to build Domain-Driven Design application, one of good (I won't say best) practices is to create so-called application services between the UI and the Domain. They are similar to stateless business objects you mentioned, but should contain almost no logic. They should look like this:
public void SayHello(int id, String helloString)
{
SomeDomainObject target = domainObjectRepository.findById(id); //This uses Hibernate to load the object.
target.sayHello(helloString); //There is a single domain object method invocation per application service method.
domainObjectRepository.Save(target); //This one is optional. Hibernate should already know that this object needs saving because it tracks changes.
}
Any changes to objects contained by DomainObject (also adding objects to collections) will be handled by Hibernate.
You will also need some kind of AOP to intercept application service method invocations and create Hibernate's session before the method executes and save changes after method finishes with no exceptions.
There is a really good sample how to do DDD in Java here. It is based on the sample problem from Eric Evans' 'Blue Book'. The application logic class sample code is here.

What's the difference between a Controller and a Service?

I'm looking for how to structure the layer of my app between the presentation layer and the model / business object layer. I see examples using Controller classes and others using Service classes. Are these the same things with different names for different methodologies, or is there a more fundamental difference?
Edit:
To put the question in context, this is a PHP app using Doctrine as the ORM.
I would say terms like Controller are basically same names for potentially very different things depending on what methodology / framework you are using. At a very high level, they may perform the same action - hence the generic name usage - but their responsibilities and scope within the context of the framework will usually be much more specific and different.
Eg: The Controller in MVC has little or nothing in common with the Controller layer in WCSF.
I think these terms like Controller / Service etc are generic and hence have been used in many frameworks but they have a special meaning within the framework of reference.
Also, specifically, a controller and a service to me are two completely differing concepts.
Controller is something like a layer that is responsible for orchestrating logic within the application / or an aspect of the application
Service , to me, is basically the external API through which you expose aspects of your application in a standard manner

Repository, Service or Domain object - where does logic belong?

Take this simple, contrived example:
UserRepository.GetAllUsers();
UserRepository.GetUserById();
Inevitably, I will have more complex "queries", such as:
//returns users where active=true, deleted=false, and confirmed = true
GetActiveUsers();
I'm having trouble determining where the responsibility of the repository ends. GetActiveUsers() represents a simple "query". Does it belong in the repository?
How about something that involves a bit of logic, such as:
//activate the user, set the activationCode to "used", etc.
ActivateUser(string activationCode);
Repositories are responsible for the application-specific handling of sets of objects. This naturally covers queries as well as set modifications (insert/delete).
ActivateUser operates on a single object. That object needs to be retrieved, then modified. The repository is responsible for retrieving the object from the set; another class would be responsible for invoking the query and using the object.
These are all excellent questions to be asking. Being able to determine which of these you should use comes down to your experience and the problem you are working on.
I would suggest reading a book such as Fowler's patterns of enterprise architecture. In this book he discusses the patterns you mention. Most importantly though he assigns each pattern a responsibility. For instance domain logic can be put in either the Service or Domain layers. There are pros and cons associated with each.
If I decide to use a Service layer I assign the layer the role of handling Transactions and Authorization. I like to keep it 'thin' and have no domain logic in there. It becomes an API for my application. I keep all business logic with the domain objects. This includes algorithms and validation for the object. The repository retrieves and persists the domain objects. This may be a one to one mapping between database columns and domain properties for simple systems.
I think GetAtcitveUsers is ok for the Repository. You wouldnt want to retrieve all users from the database and figure out which ones are active in the application as this would lead to poor performance. If ActivateUser has business logic as you suggest, then that logic belongs in the domain object. Persisting the change is the responsibility of the Repository layer.
Hope this helps.
When building DDD projects I like to differentiate two responsibilities: a Repository and a Finder.
A Repository is responsible for storing aggregate roots and for retrieving them, but only for usage in command processing. By command processing I meant executing any action a user invoked.
A Finder is responsible for querying domain objects for purposes of UI, like grid views and details views.
I don't consider finders to be a part of domain model. The particular IXxxFinder interfaces are placed in presentation layer, not in the domain layer. Implementation of both IXxxRepository and IXxxFinder are placed in data access layer, possibly even in the same class.

FluentNHibernate Unit Of Work / Repository Design Pattern Questions

I think I am at a impasse here. I have an application I built from scratch using FluentNHibernate (ORM) / SQLite (file db). I have decided to implement the Unit of Work and Repository Design pattern. I am at a point where I need to think about the end game, which will start as a WPF windows app (using MVVM) and eventually implement web services / ASP.Net as UI.
Now I already created domain objects (entities) for ORM. And now I don't know how should I use it outside of ORM. Questions about it include:
Should I use ORM entity objects directly as models in MVVM? If yes, do I put business logic (such as certain values must be positive and be greater than another Property) in those entity objects? It is certainly the simpler approach, and one I am leaning right now. However, will there be gotchas that would trash this plan?
If the answer above is no, do I then create a new set of classes to implement business logic and use those as Models in MVVM? How would I deal with the transition between model objects and entity objects? I guess a type converter implementation would work well here.
To answer the first part of your question, yes your business logic and validation should go in your entities. The point of NHibernate is to let you design your entities to be persistence ignorant. That means that you should, whenever possible, be designing your entities as you would if you didn't care about persistence. This isn't entirely feasible as you'll soon find out (you'll need to make your properties virtual in order to support lazy loading and if you want to use NHibernate Validator you'll be decorating your properties with validation attributes), but for the most part NHibernate does a good job of staying out of your way.
As for whether to use your entities as the models, you'll get mixed reviews on that. Ideally, you would create separate viewmodel classes and map from your entities to the viewmodel so that your views will only access to the bare minimum of information they need. This also goes a long way in preventing N+1 access issues. However, doing so is often a huge pain. Granted, there are tools like AutoMapper that will make it easier from transposing your entity properties to a viewmodel.