DDD - injecting Factories in aggregate root Entity constructor - entity

I'm writing an app with DDD in mind and trying to avoid having an anemic domain model by delegating doman logic and behaviour to entities. There's an issue I'm running into with constructing entities that are aggregate roots and need to create sub-entities that require handling by a factory class. Here's an example:
I have the following entities: Page, Url and Layout. What makes a Page in my model is a Page with a Url and a Layout - without those two, a Page object would not be valid. In a simple model, the Page constructor method would simply create those two objects as private attributes. However, the Url has a specific requirement; it has to be created from the Page's title - or a slug - and it has to be unique (ensured by appending "-1", "-2", or something similar). This requires communication with a repository.
My initial idea was to pass/inject a UrlFactory object to the Page constructor and have the Page create the Url it needs, but I keep reading about how injecting services into entities is a bad idea.
So, my question is; is there a way - or an established pattern - to allow entities to construct their complex sub-entities without having an anemic domain model, or is injecting a factory in case such as this a valid solution?

If you consider URL construction as a technical concern, you could have an UrlFactory in the Infrastructure layer
in C# :
public class UrlFactory
{
public string CreateUrl(string title)
{
var url = // ... construct URL from the title here
return _pageRepository.NextAvailableUrlLike(url);
}
}
and then call it from your Application layer service.
If you see it as a Domain concern, Url construction logic could be in a Domain Service instead. The line calling the repository would be moved to the Application layer Service :
public void CreatePage(string title)
{
var potentialUrl = _urlService.CreateUrl(title);
var realUrl = _pageRepository.NextAvailableUrlLike(url)
new Page(title, realUrl, ...); // do whatever you want with the new Page instance
}

Do not inject factory class into aggregrate, use factory method instead. Then create method "validate(Validator)" in aggregate (Aggregate will only know it can be valided, but it will not implement logic how to do it).
Validator class which will be passed as parameter to your validate method, will need to have one method ->validateObject(this).
You pass instance of aggregate into validateObject so it will have access to your properties.
Validator class can have injected repository. When you run validateObject method it will search database for uniquness.

Related

Having more than one entity context

Let's say I've extended identity framework dbContext to build my own, and I've our authenticated controller who get injected with the dbContext and fetch an entity related with the current ApplicationUser, entity framework will relate the two entities leading to a server error because of circular references.
We don't want to serialize circular references.
So we create a new dbContext in the method who istantiate a new dbcontext and query the unrelated entities, this will work. But this is not testable, we don't want our controller to strictly depends on the dbContext, we want it to be injected.
So we add a second parameter, in the constructor, unfortunately this will make the system inject the same dbContext twice, not so useful.
We tried to create a class fakeDbContext who inherit from dbContext and add it services and use it, but now we got two dbcontext, who can potentially generate migrations and configurations and errors...
Which is the right way of doing this in the new MVC6 ?
Edit...
I found out that if my controller require an IEnumerable<dbContext> i get all the object registered as service of that type, so just doubling the part in startup.cs where we add the dbContext in the service registration area i get two of them...
The drawback here is that i don't know wich one is the virgin one, it looks like it goes in order of registration, but i have no clue, if this will change.
Edit 2 ...
I've created a TransientDbService class who have just a factory method taking the IserviceProvider, it use it to get the options to construct the dbContext, and then expose it. I've registered it as transient, then in the controller i require this service type.
the drawback here is if i'll ever need a third dbContext i should write more code, more code means errors and maintaning it.
Edit 3 ...
Not having two dbContext at all. The following setting allow me to have no relationships valorized.
Database.ChangeTracker.QueryTrackingBehavior = Microsoft.Data.Entity.QueryTrackingBehavior.NoTracking;
The drawback here is that i can't use my model graph, making everything more complex...
Edit 4 ...
https://github.com/aspnet/DependencyInjection/issues/352
You are right to think that no tracking queries will help in some cases, but other times you'll need to have more than one instance of the DbContext created.
You normally use the AddDbContext<TContext>() method in startup to make sure an instance of your context type is created per request and the right DbContextOptions and service provider get set on it. When you need to deviate from this pattern you have a few options, e.g.:
Include a constructor in your derived DbContext class that takes an IServiceProvider and passes it to the base constructor. Make sure your controller takes IServiceProvider. Once you do this you should be able to create DbContext manually with something like this:
using(var context1 = new MyDbContext(serviceProvider),
var context2 = new MyDbContext(serviceProvider))
{ ...
To avoid having to change the constructor signatures on your derived DbContext type you can take advantage of the DbContextActivator class (it is our Internal namespace), e.g.:
using(var context1 = DbContextActivator.CreateInstance<MyDbContext>(serviceProvider),
var context2 = DbContextActivator.CreateInstance<MyDbContext>(serviceProvider)
{...
Note: If you are still using AddDbContext<MyDbContext>(options => ...) in startup it should pull those options automatically from the service provider. But you can also choose to either include the DbContextOptions as a parameter in the constructor or override the OnConfiguring() method for that.
I am giving you examples that create two separate DbContexts in a using block, but you should also be able to mix those with the regular "per-request" DbContext you would get injected in the controller's constructor.
Besides these options currently available I have created a new issue to track other possible improvements on how to create multiple instance of the same DbContext type in the same request:
https://github.com/aspnet/EntityFramework/issues/4441

Expose only a part of my class

Lets say i have a Class User with multiple properties. I'm building a REST based App so in my homepage when I request for "user details" I need only a few properties from my User and rest from other classes. How do i write the class for the object which i would return for "user details" ?
My current design retrieves the needed properties from the class to build the JSON. I hope there is a better way to handle this.
I use Play Framework 2.0 with Java
If you don't want to expose whole business class User, I'll build a second class, a DTO. This class provides only the desired data to be transfered by REST API.
User user = new User("admin");
// Set other properties
UserDetailsDTO userDetailsDTO = new UserDetails(user); //<- Transfer userDetailsDTO
Or if "user details" are important for your application, maybe you should consider to create a UserDetails class and use it inside your User class by composition.
public class User {
Long id;
String name;
String address;
UserDetails userDetails; // Composition <- Tranfer userDetails
}
Note: example where don in Java
Looks like you need a Facade: http://en.wikipedia.org/wiki/Facade_pattern.
It is a simple pattern that helps you expose methods/properties from a multiple classes.
You can store references to objects in your Facade class and expose only those things you need.
There is an option of creating a View Model object, providing proper abstraction for the information required for that JSON.
More details about it here: http://en.wikipedia.org/wiki/Model_View_ViewModel
But this is typically used in the cases where view directly used in Views of the application. So careful analysis is required in use case mentioned above, since there is already JSON being created, creation of this View Model layer is really justified.

Differences between Proxy and Decorator Pattern

Can you give any good explanation what is the difference between Proxy and Decorator?
The main difference I see is that when we assume that Proxy uses composition and Decorator uses aggregation then it seems to be clear that by using multiple (one or more) Decorators you can modify/ add functionalities to pre-existing instance (decorate), whereas Proxy has own inner instance of proxied class and delegates to it adding some additional features (proxy behaviour).
The question is - Does Proxy created with aggregation is still Proxy or rather Decorator? Is it allowed (by definition in GoF patterns) to create Proxy with aggregation?
The real difference is not ownership (composition versus aggregation), but rather type-information.
A Decorator is always passed its delegatee. A Proxy might create it himself, or he might have it injected.
But a Proxy always knows the (more) specific type of the delegatee. In other words, the Proxy and its delegatee will have the same base type, but the Proxy points to some derived type. A Decorator points to its own base type. Thus, the difference is in compile-time information about the type of the delegatee.
In a dynamic language, if the delegatee is injected and happens to have the same interface, then there is no difference.
The answer to your question is "Yes".
Decorator Pattern focuses on dynamically adding functions to an object, while Proxy Pattern focuses on controlling access to an object.
EDIT:-
Relationship between a Proxy and the real subject is typically set at compile time, Proxy instantiates it in some way, whereas Decorator is assigned to the subject at runtime, knowing only subject's interface.
Here is the direct quote from the GoF (page 216).
Although decorators can have similar implementations as proxies, decorators have a different purpose. A decorator adds one or more responsibilities to an object, whereas a proxy controls access to an object.
Proxies vary in the degree to which they are implemented like a decorator. A
protection proxy might be implemented exactly like a decorator. On the other
hand, a remote proxy will not contain a direct reference to its real subject but only
an indirect reference, such as "host ID and local address on host." A virtual proxy
will start off with an indirect reference such as a file name but will eventually
obtain and use a direct reference.
Popular answers indicate that a Proxy knows the concrete type of its delegate. From this quote we can see that is not always true.
The difference between Proxy and Decorator according to the GoF is that Proxy restricts the client. Decorator does not. Proxy may restrict what a client does by controlling access to functionality; or it may restrict what a client knows by performing actions that are invisible and unknown to the client. Decorator does the opposite: it enhances what its delegate does in a way that is visible to clients.
We might say that Proxy is a black box while Decorator is a white box.
The composition relationship between wrapper and delegate is the wrong relationship to focus on when contrasting Proxy with Decorator, because composition is the feature these two patterns have in common. The relationship between wrapper and client is what differentiates these two patterns.
Decorator informs and empowers its client.
Proxy restricts and disempowers its client.
Decorator get reference for decorated object (usually through constructor) while Proxy responsible to do that by himself.
Proxy may not instantiate wrapping object at all (like this do ORMs to prevent unnecessary access to DB if object fields/getters are not used) while Decorator always hold link to actual wrapped instance.
Proxy usually used by frameworks to add security or caching/lazing and constructed by framework (not by regular developer itself).
Decorator usually used to add new behavior to old or legacy classes by developer itself based on interface rather then actual class (so it work on wide range of interface instances, Proxy is around concrete class).
Key differences:
Proxy provides the same interface. Decorator provides an enhanced interface.
Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests.
Decorator can be viewed as a degenerate Composite with only one component. However, a Decorator adds additional responsibilities - it isn't intended for object aggregation.
Decorator supports recursive composition
The Decorator class declares a composition relationship to the LCD (Lowest Class Denominator) interface, and this data member is initialized in its constructor.
Use Proxy for lazy initialization, performance improvement by caching the object and controlling access to the client/caller
Sourcemaking article quotes the similarities and differences in excellent way.
Related SE questions/links:
When to Use the Decorator Pattern?
What is the exact difference between Adapter and Proxy patterns?
Proxy and Decorator differ in purpose and where they focus on the internal implementation. Proxy is for using a remote, cross process, or cross-network object as if it were a local object. Decorator is for adding new behavior to the original interface.
While both patterns are similar in structure, the bulk of the complexity of Proxy lies in ensuring proper communications with the source object. Decorator, on the other hand, focuses on the implementation of the added behavior.
Took a while to figure out this answer and what it really means. A few examples should make it more clear.
Proxy first:
public interface Authorization {
String getToken();
}
And :
// goes to the DB and gets a token for example
public class DBAuthorization implements Authorization {
#Override
public String getToken() {
return "DB-Token";
}
}
And there is a caller of this Authorization, a pretty dumb one:
class Caller {
void authenticatedUserAction(Authorization authorization) {
System.out.println("doing some action with : " + authorization.getToken());
}
}
Nothing un-usual so far, right? Obtain a token from a certain service, use that token. Now comes one more requirement to the picture, add logging: meaning log the token every time. It's simple for this case, just create a Proxy:
public class LoggingDBAuthorization implements Authorization {
private final DBAuthorization dbAuthorization = new DBAuthorization();
#Override
public String getToken() {
String token = dbAuthorization.getToken();
System.out.println("Got token : " + token);
return token;
}
}
How would we use that?
public static void main(String[] args) {
LoggingDBAuthorization loggingDBAuthorization = new LoggingDBAuthorization();
Caller caller = new Caller();
caller.authenticatedUserAction(loggingDBAuthorization);
}
Notice that LoggingDBAuthorization holds an instance of DBAuthorization. Both LoggingDBAuthorization and DBAuthorization implement Authorization.
A proxy will hold some concrete implementation (DBAuthorization) of the base interface (Authorization). In other words a Proxy knows exactly what is being proxied.
Decorator:
It starts pretty much the same as Proxy, with an interface:
public interface JobSeeker {
int interviewScore();
}
and an implementation of it:
class Newbie implements JobSeeker {
#Override
public int interviewScore() {
return 10;
}
}
And now we want to add a more experienced candidate, that adds it's interview score plus the one from another JobSeeker:
#RequiredArgsConstructor
public class TwoYearsInTheIndustry implements JobSeeker {
private final JobSeeker jobSeeker;
#Override
public int interviewScore() {
return jobSeeker.interviewScore() + 20;
}
}
Notice how I said that plus the one from another JobSeeker, not Newbie. A Decorator does not know exactly what it is decorating, it knows just the contract of that decorated instance (it knows about JobSeeker). Take note here that this is unlike a Proxy; that, in contrast, knows exactly what it is decorating.
You might question if there is actually any difference between the two design patterns in this case? What if we tried to write the Decorator as a Proxy?
public class TwoYearsInTheIndustry implements JobSeeker {
private final Newbie newbie = new Newbie();
#Override
public int interviewScore() {
return newbie.interviewScore() + 20;
}
}
This is definitely an option and highlights how close these patterns are; they are still intended for different scenarios as explained in the other answers.
A Decorator adds extra responsibility to an object, while a proxy controls access to an object, they both use composition. If your wrapper class messes with the subject, it is obviously a proxy. Let me explain by a code example in PHP:
Code Example
Given is the following CarRepository:
interface CarRepositoryInterface
{
public function getById(int $id) : Car
}
class CarRepository implements CarRepositoryInterface
{
public function getById(int $id) : Car
{
sleep(3); //... fake some heavy db call
$car = new Car;
$car->setId($id);
$car->setName("Mercedes Benz");
return $car;
}
}
CarRepository-Proxy
A Proxy is often used as lazy loading or a cache proxy:
class CarRepositoryCacheProxy implements CarRepositoryInterface
{
private $carRepository;
private function getSubject() : CarRepositoryInterface
{
if($this->carRepository == null) {
$this->carRepository = new CarRepository();
}
return $this->carRepository;
}
/**
* This method controls the access to the subject
* based on if there is cache available
*/
public function getById(int $id) : Car
{
if($this->hasCache(__METHOD__)) {
return unserialize($this->getCache(__METHOD__));
}
$response = $this->getSubject()->getById($id);
$this->writeCache(__METHOD__, serialize($response));
return $response;
}
private function hasCache(string $key) : bool
{
//... implementation
}
private function getCache(string $key) : string
{
//... implementation
}
private function writeCache(string $key, string $result) : string
{
//... implementation
}
}
CarRepository-Decorator
A Decorator can be used as long as the added behavior does not "control" the subject:
class CarRepositoryEventManagerDecorator implements CarRepositoryInterface
{
private $subject, $eventManager;
/**
* Subjects in decorators are often passed in the constructor,
* where a proxy often takes control over the invocation behavior
* somewhere else
*/
public function __construct(CarRepositoryInterface $subject, EventManager $eventManager)
{
$this->subject = $subject;
$this->eventManager = $eventManager;
}
public function getById(int $id) : Car
{
$this->eventManager->trigger("pre.getById");
//this method takes no control over the subject
$result = $this->subject->getById($id);
$this->eventManager->trigger("post.getById");
return $result;
}
}
Proxy provides the same interface to the wrapped object, Decorator provides it with an enhanced interface, and Proxy usually manages the life cycle of its service object on its own, whereas the composition of Decorators is always controlled by the client.
Let me explain the patterns first and then come to you questions.
From the class diagram and meanings, they are very similar:
Both have the same interface as its delegatee has.
Both add/enhance the behavior of its delegatee.
Both ask the delegatee to perform operations(Should not work with null delegatee).
But they have some difference:
Different intents:
Proxy enhances the behavior of delegatee(passed object) with quite different domain knowledge from its delegatee. Eg, a security proxy adds security control of the delegatee. A proxy to send remote message needs to serialize/deserialize data and has knowlege on network interfacing, but has nothing to do with how to prepare source data.
Decorator helps on the same problem domain the delegatee works on. Eg, BufferedInputStreaman(an IO decorator) works on input, which is the same problem domain(IO) as its delegatee, but it cannot perform without a delegatee which provides IO data.
Dependency is strong or not:
Decorator relies on delegate to finish the behavior, and it cannot finish the behavior without delegatee(Strong). Thus we always use aggration over composition.
Proxy can perform faked behavior even it does not need a delegatee(Weak). Eg, mockito(unit test framework) could mock/spy a behavior just with its interface. Thus we use composition to indicate there's no strong dependency on real object.
Enhance multipletimes(as mentioned in question):
Proxy: we could utilize proxy to wrap real object once not several times.
Decorator: A decorator can wrap the real object several times or can wrap the object which is already wrapped by a decorator(which could be both a different decorator or the same decorator). Eg, for an order system, you can do discount with decorators.
PercentageDiscountDecorator is to cut 50% off, and DeductionAmountDiscountDecorator is to deduct 5$ directly if the amount is greater than 10$(). So,
1). When you want to cut 50% off and deduct 5$, you can do: new DeductionAmountDiscountDecorator(new PercentageDiscountDecorator(delegatee))
2). When you want to deduct 10$, you can do new DeductionAmountDiscountDecorator(new DeductionAmountDiscountDecorator(delegatee)).
The answer to the question has nothing to do with the difference between Proxy and Decorator. Why?
Design patterns just patterns for people who are not good at OO skills to make use of OO solutions. If you are familiar with OO, you don't need to know how many design patterns there(Before design patterns invented, with the same prolbem skilled people could figure out the same solution).
No two leaves are exactly the same, so as the problems you encount. People will always find their problems are different from the problems given by design patterns.
If your specified problem is really different from both problems that Proxy and Decorator work on, and really needs an aggregation, why not to use? I think to apply OO to your problem is much more important than you label it a Proxy or Decorator.

Business rules validation in NHibernate Validator

Is it possible to define a validation method (for businbess rules validation) that will be used by NHibernate.Validator?
I mean something that exists in EntLib:
[HasSelfValidation()]
public class SomeClass
{
//...
[SelfValidation()]
public virtual void DoValidate(ValidationResults results)
{
//...
}
}
Yes, it can be done - but you will be missing a way to communicate more information on which rules were violated in the case of validation errors.
NHibernate Validator, to my knowledge, only provides the ability to specify a text message, the name of the class, and - in the case of property level validation attributes - the name of the violated property.
If your attribute HasSelfValidationAttribute implement IRuleArgs pointing to an IValidator (or IInitializableValidator), it has no way to communicate back anything else but a simple string Message and the name of the class, which would probably be too little information if your demand is to validate "real business rules".
NHibernate Validator is great for simple validation scoped to the properties of a class, but it comes short when you need to do more complex validation.
Have a look at The RulesEngine Project. Your business object won't have to be decorated with any attributes or have to implement any interfaces...

Getting real instance from proxy under Unity Interception with NHibernate

I'm using Unity to resolve types dynamically for a pluggable architecture. I'm also using interception to apply business rule validation via AOP (using ValidationAspects). Finally, I'm using NHibernate as an ORM to persist domain objects.
In order for AOP to work, we use the VirtualMethodInterceptor, as interface interception doesn't work with NHibernate. I have a facade over ISession that handles casting between interface and real types for repository operations.
To make sure that all objects in the graph fetched via NHibernate are properly proxied for AOP, I made an NH IInterceptor implementation and overrode the Instantiate() method, so I could supply NH with created objects rather than have it call new(). I then use Container.Resolve() to get back proxied objects with the validation injected, and give this back to NH to populate. This works OK.
The problem comes when the session flush occurs. NHibernate gets upset because the objects it sees in the graph are of the proxy type rather than the real type. The way we're mapping (all via property, all virtual) NH should be able to get all the values it needs via the proxy, if I could override the type-checking.
What I need to know is: given a transparently proxied object created by Unity with Interception enabled, is there a) any way to obtain a direct reference to the 'real' instance it's proxying, or b) to override NH and tell it to treat objects of a proxy type as if it were of a known mapped type, dynamically at runtime?
We use interception for caching. So in our class, that implements ICallHandler we have code like this:
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
//...
var nextHandler = getNext();
var realReturn = nextHandler(input, getNext);
var cacheRefreshingItemParameters = new CacheRefreshingItemParameters
{
InterfaceMethod = input.MethodBase,
InterfaceType = input.MethodBase.DeclaringType,
TargetType = input.Target.GetType() //remember original type
};
_cacheProvider.Add(cacheKey, realReturn.ReturnValue, cacheRefreshingItemParameters);
//...
return (cachedReturn);
}
We put cacheRefreshingItemParameters in cache UpdateCallback and then resolve original service:
var service = _unityContainer.Resolve(parameters.TargetType);