I'm learning about Domain-Driven-Design and I'm a little confused about entities and injecting domain services into them. I have found this blog and conclusion is that injecting services into entities is a bad idea. I partially agree with that, but what to do in this case:
I have User entity which is an aggregate root, which has Password value object in it. It look like this:
Password value object:
public class Password
{
public string Hash { get; private set; }
public string Salt { get; private set; }
private readonly IHashGeneratorService _hashGeneratorService;
public Password(IHashGeneratorService hashGeneratorService)
{
_hashGeneratorService = hashGeneratorService;
}
public void GenerateHash(string inputString)
{
//Some logic
Salt = hashGeneratorService.GenerateSalt();
Hash = hashGeneratorService.GenerateHash(inputString);
}
}
User entity:
public class User
{
public Password Password { get; private set; }
public User(IHashGeneratorService hashGeneratorService)
{
this.Password = new Password(hashGeneratorService);
}
}
In this case if I create User entity via factory I need to provide IHashGeneratorService implementation to factory constructor or Create() method. After that if my factory is used by, for ex. SomeUserService I have to provide implementation (ex. via ctor injection) to it. And so on...
Honestly it smells form me, as lot of my classess are dependent on hash generator service implementation but only Password class uses it. And it also breaks SRP principle for Password class as I assume.
I've found out some solutions:
Use service locator. But it also smells as it's an anti-pattern and it is hard to test and manage entities if we use it.
Implement hashing alghoritm directly inside Password methods.
Stay with that what I have :) Cons are mentioned above, pros are that my classess are easier to test as I can provide mocked service instead of full implementation.
Personally I tend to refoactor my code to second solution as it does not break SRP (or it does? :)), classess are not dependent of hashing service implementation. Something more?
Or do you have another solutions?
I am quite new to DDD, however I belive that hashing passwords is not a concern of the domain, but a technical concern, just like persistence. The hash service should have it's interface defined in the domain, but it's implementation in the infrastructure layer. The application service would then use the hash service to hash the password and create a Password instance (which should be a value object) before passing it to the User aggregate root.
There might be cases where an aggregate has to use a service like when the dependency resolutions are very complex and domain-specific. In this case, the application service could pass a domain service into the aggregate method. The aggregate would then double-dispatch to the service to resolve references.
For more information you can read the Implementing Domain-Driven Design book written by Vaughn Vernon. He speaks about this around page 362 (Model Navigation), but also at a few other places in the book.
I don't know reasons, why do you consider injection of constructor parameters only. AFAIK, it's a common feature for DI-containers to inject properties or fields. E.g., using MEF you could write something like this:
class SomeUserService : ISomeUserService
{
[Import]
private IHashGeneratorService hashGeneratorService { get; set; }
// ...
}
and inject a dependency only in those types, where you really need it.
Related
For the sake of this example, I have a "User" class that needs to receive access to my EmailService.
Whenevera a new user instance is created ( var user = new User(emailServiceInstance); ) I do not want EmailService instance to be included as a parameter because not all callers will be aware of it. I want Ninject to inject it.
So normally a binding for the EmailService would look something like this:
kernel.Bind<IEmailService>().To<EmailService>().InSingletonScope();
But I would like to include more parameters in my User class constructor. I would like to pass some parameters and have EmailService injected as well. Is this possible?
From its callers, User class would be instanciated with something like:
var user = new User(firstName,LastName, [notsure])
And then my User class constructor would look like this:
public User(string firstName, stringLastName, EmailService emailService)
First and Lastname would be passed in and email service would be instantiated/injected with Ninject.
Is it possible? What would be the correct syntax to create this binding ?
Neither Constructor Injection nor Property Injection are a good fit for your scenario. In section 4.3 of DIPP&P, Mark Seemann and I state that:
Entities that contain behavior besides their usual set of data members would easily get a wide range of methods, each requiring their own dependencies. Although you might be tempted to use Constructor Injection to inject such dependencies, that leads to a situation where each such entity needs to be created with all of its dependencies, even though only a few may be necessary for a given use case. This complicates testing the logic of an entity, because all dependencies need to be supplied to the constructor, even though a test might only be interested in a few dependencies. Method Injection [...] offers a better alternative.
Using Method Injection, your User entity would become something as follows:
public class User
{
public string FirstName { get; }
public string LastName { get; }
public string PasswordHash { get; }
public User(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
public void ResetPassword(
IEmailService mailService, IPasswordGenerator generator)
{
var password = generator.Generate();
this.PasswordHash = generator.Hash(password);
// Warning: this is just an example, but not a good security practice.
// Mailing passwords is a good way to be shamed on plaintextoffenders.com
mailService.SendMail($#"
Hello {this.FirstName}
We have received new password request for your account.
Your new password is: {password}.");
}
}
Notice that the ResetPassword method does not store its incoming dependencies. This is deliberate and this is what makes Method Injection different from both Constructor Injection and Property Injection. When dependencies are applied to a class after construction (which is what happens with Property Injection), it leads to Temporal Coupling. By letting the method use the dependency, but not store the dependency, it prevents Temporal Coupling from occurring.
A more detailed discussion about Method Injection and how to apply it to classes like entities can be found in section 4.3 of Dependency Injection Principles, Practices, and Patterns.
I have debated this for a while now and still have not come to a conclusion.
While most examples I see have the factories code in the application layer I tend to think it should be in the domain layer.
Reasons for this:
I sometimes have initial validation done in my factory where I want all creation of objects to go through.
I want this code to be used on all instantiates of my object.
Sometimes an operation requires parameter information which feels unnatural to pass to a constructor.
And a few more not as important reasons.
Are there reasons why this is a bad practice?
Does this break other patterns?
A factory in DDD is just an instance of the factory pattern and as such it should be used where it makes the most sense. Another principle to consider is the information expert pattern which essentially states that behavior should be assigned to classes closest to the information. Therefore, if you have some domain specific rules and logic you would like to enforce, place the factory in the domain layer - after all, the factory creates domain objects. Note however that you may have other types of factories in other layers.
From memory, Eric Evans' book has examples where object factories are very much part of the domain layer.
For me, it makes perfect sense to locate your factories here.
+1 for doing that. Accessibility would be a good reason, I would keep the creational code at least close to the domain model layer. Otherwise users of the domain model will get simply confused how to instantiate it specially when finding restricted access constructors. Actually one sound reason to separate it would be that you have different valid ways to create the same thing e.g. which is the case usually when employing the Abstract Factory.
If I had to separate it I would put it in e.g. a package (in the case of Java) at least the same level of the domain model and ship it always along with it e.g.
upper
--> domain
--> domain_factory
I prefer Factories in the Application Layer.
If you keep the Factories in the Domain Layer, they will not help you when you need complex types as parameters (C# code example):
Application Layer:
//this Factory resides in the Domain Layer and cannot reference anything else outside it
Person person = PersonAggregateFactory.CreateDeepAndLargeAggregate(
string name, string code, string streetName,...
and lots of other parameters...);
//these ones reside in Application Layer, thus can be much more simple and readable:
Person person = PersonAggregateFactory.CreateDeepAndLargeAggregate(CreatePersonCommand);
Person person = PersonAggregateFactory.CreateDeepAndLargeAggregate(PersonDTO);
Domain Layer:
public class Person : Entity<Person>
{
public Address Address {get;private set;}
public Account Account {get;private set;}
public Contact Contact {get;private set;}
public string Name {get;private set;}
public Person(string name, Address address,Account account, Contact contact)
{
//some validations & assigning values...
this.Address = address;
//and so on...
}
}
public class Address:Entity<Address>{
public string Code {get;private set;}
public string StreetName {get;private set;}
public int Number {get;private set;}
public string Complement {get;private set;}
public Address(string code, string streetName, int number, string complement?)
{
//some validations & assigning values...
code = code;
}
}
public class Account:Entity<Account>{
public int Number {get;private set;}
public Account(int number)
{
//some validations & assigning values...
this.Number = number;
}
}
//yout get the idea:
//public class Contact...
Also, there is no obligation on keeping Factories inside the Domain Layer (from Domain Driven Design Quickly):
Therefore, shift the responsibility for creating instances of complex
objects and Aggregates to a separate object, which may itself have
no responsibility in the domain model but is still part of the
domain design. Provide an interface that encapsulates all complex
assembly and that does not require the client to reference the
concrete classes of the objects being instantiated. Create entire
Aggregates as a unit, enforcing their invariants.
As I don't use Factories to load persisted objects into memory, they don't have to be accessible from other layers than Application's. Here's why (from Domain Driven Design Quickly):
Another observation is that Factories need to create new objects
from scratch, or they are required to reconstitute objects which
previously existed, but have been probably persisted to a
database. Bringing Entities back into memory from their resting
place in a database involves a completely different process than
creating a new one. One obvious difference is that the new
object does not need a new identity. The object already has one.
Violations of the invariants are treated differently. When a new
object is created from scratch, any violation of invariants ends
up in an exception. We can’t do that with objects recreated from
a database. The objects need to be repaired somehow, so they
can be functional, otherwise there is data loss.
If builders/factories only have dependencies on domain classes and primitives, place them in the domain layer, otherwise place them outside the domain layer.
CAREFUL with placing 'implementation' in the Domain Layer.
Your domain code doesn't have dependencies. So, you are in trouble if you need to have complex factories.
For example:
// DOMAIN LAYER
public interface IAggregateFactory<TAgg, in TInput>
{
Task<TAgg> CreateAsync(TInput input);
}
public class AvailabilityFactoryParameters
{
public string SomeInputParameter { get; set; }
public string ZipCode { get; set; }
}
// INFRASTRUCTURE/APPLICATION LAYER
public class AvailabilityFactory : IAggregateFactory<GamePredictorAggregate,
GamePredictorFactoryParameters>
{
private readonly HttpClient _httpClient;
public AvailabilityFactory(IHttpClientFactory factory)
{
_httpClient = factory.CreateClient("weatherApi");
}
public async Task<GamePredictorAggregate> CreateAsync(GamePredictorFactoryParameters input)
{
var weather = await _httpClient.GetFromJsonAsync<WeatherDto>($"/weather/{input.ZipCode}");
return new GamePredictorAggregate(weather.CurrentTemperature, input.SomeInputParameter);
}
}
public class WeatherDto
{
public double CurrentTemperature { get; set; }
}
As you can see, now you have a myriad of objects and dependencies available to enrich your factory experience.
So, when you use it in your Application Service, it is easy...
public class GamePredictionService : ApplicationService
{
private readonly IAggregateFactory<GamePredictorAggregate, GamePredictorFactoryParameters> _factory;
public GamePredictionService(IAggregateFactory<GamePredictorAggregate, GamePredictorFactoryParameters> factory)
{
_factory = factory;
}
public async Task CreateNewPredictor(string zipCode, int someOtherParamater)
{
var input = new GamePredictorFactoryParameters();
input.ZipCode = zipCode;
input.SomeInputParameter = someOtherParamater;
var aggregate = await _factory.CreateAsync(input);
// Do your biz operations
// Persist using repository
}
}
Now your application service doesn't need to worry about the internals, and your domain objects need to understand how the factory gives them 'birth.'
Summary: Having your implementation in the Domain layer makes only sense if your factory only needs primitive types and nothing else. In cases where you may need to gather data from external services or other application services' DTOs, you want to move the implementation outside.
The only 'drawback' is that you need to 'inject' the factory into your application service, but that's not a big deal.
I hope this answer helps to clarify 'where to place Factories.'
I am newbie to SOA though I have some experience in OOAD.
One of the guidelines for SOA design is “Use Abstract Classes for Modeling only. Omit them from Design”. The use of abstraction can be helpful in modeling (analysis phase).
During analysis phase I have come up with a BankAccount base class. The specialized classes derived from it are “FixedAccount” and “SavingsAccount”. I need to create a service that will return all accounts (list of accounts) for a user. What should be the structure of service(s) to meet the requirement?
Note: It would be great if you can provide code demonstration using WCF.
It sounds like you are trying to use SOA to remotely access your object model. You would be better of looking at the interactions and capabilities you want your service to expose and avoid exposing inheritance details of your services implementation.
So in this instance where you need a list of user accounts your interface would look something like
[ServiceContract]
interface ISomeService
{
[OperationContract]
Collection<AccountSummary> ListAccountsForUser(
User user /*This information could be out of band in a claim*/);
}
[DataContract]
class AccountSummary
{
[DataMember]
public string AccountNumber {get;set;}
[DataMember]
public string AccountType {get;set;}
//Other account summary information
}
if you do decide to go down the inheritance route, you can use the KnownType attribute, but be aware that this will add some type information into the message being sent across the wire which may limit your interoperability in some cases.
Update:
I was a bit limited for time earlier when I answered, so I'll try and elaborate on why I prefer this style.
I would not advise exposing your OOAD via DTOs in a seperate layer this usually leads to a bloated interface where you pass around a lot of data that isn't used and religously map it into and out of what is essentially a copy of your domain model with all the logic deleted, and I just don't see the value. I usually design my service layer around the operations that it exposes and I use DTOs for the definition of the service interactions.
Using DTOs based on exposed operations and not on the domain model helps keep the service encapsulation and reduces coupling to the domain model. By not exposing my domain model, I don't have to make any compromises on field visibility or inheritance for the sake of serialization.
for example if I was exposing a Transfer method from one account to another the service interface would look something like this:
[ServiceContract]
interface ISomeService
{
[OperationContract]
TransferResult Transfer(TransferRequest request);
}
[DataContract]
class TransferRequest
{
[DataMember]
public string FromAccountNumber {get;set;}
[DataMember]
public string ToAccountNumber {get;set;}
[DataMember]
public Money Amount {get;set;}
}
class SomeService : ISomeService
{
TransferResult Transfer(TransferRequest request)
{
//Check parameters...omitted for clarity
var from = repository.Load<Account>(request.FromAccountNumber);
//Assert that the caller is authorised to request transfer on this account
var to = repository.Load<Account>(request.ToAccountNumber);
from.Transfer(to, request.Amount);
//Build an appropriate response (or fault)
}
}
now from this interface it is very clear to the conusmer what the required data to call this operation is. If I implemented this as
[ServiceContract]
interface ISomeService
{
[OperationContract]
TransferResult Transfer(AccountDto from, AccountDto to, MoneyDto dto);
}
and AccountDto is a copy of the fields in account, as a consumer, which fields should I populate? All of them? If a new property is added to support a new operation, all users of all operations can now see this property. WCF allows me to mark this property as non mandatory so that I don't break all of my other clients, but if it is mandatory to the new operation the client will only find out when they call the operation.
Worse, as the service implementer, what happens if they have provided me with a current balance? should I trust it?
The general rule here is to ask who owns the data, the client or the service? If the client owns it, then it can pass it to the service and after doing some basic checks, the service can use it. If the service owns it, the client should only pass enough information for the service to retrieve what it needs. This allows the service to maintain the consistency of the data that it owns.
In this example, the service owns the account information and the key to locate it is an account number. While the service may validate the amount (is positive, supported currency etc.) this is owned by the client and therefore we expect all fields on the DTO to be populated.
In summary, I have seen it done all 3 ways, but designing DTOs around specific operations has been by far the most successful both from service and consumer implementations. It allows operations to evolve independently and is very explicit about what is expected by the service and what will be returned to the client.
I would go pretty much with what others have said here, but probably needs to add these:
Most SOA systems use Web Services for communication. Web Services expose their interface via WSDL. WSDL does not have any understanding of inheritance.
All behaviour in your DTOs will be lost when they cross the wire
All private/protected fields will be lost when they cross the wire
Imagine this scenario (case is silly but illustrative):
public abstract class BankAccount
{
private DateTime _creationDate = DateTime.Now;
public DateTime CreationDate
{
get { return _creationDate; }
set { _creationDate = value; }
}
public virtual string CreationDateUniversal
{
get { return _creationDate.ToUniversalTime().ToString(); }
}
}
public class SavingAccount : BankAccount
{
public override string CreationDateUniversal
{
get
{
return base.CreationDateUniversal + " UTC";
}
}
}
And now you have used "Add Service Reference" or "Add Web Reference" on your client (and not re-use of the assemblies) to access the the saving account.
SavingAccount account = serviceProxy.GetSavingAccountById(id);
account.CreationDate = DateTime.Now;
var creationDateUniversal = account.CreationDateUniversal; // out of sync!!
What is going to happen is the changes to the CreationDate will not be reciprocated to the CreationDateUniversal since there is no implementation crossed the wire, only the value of CreationDateUniversal at the time of serialization at the server.
I have a User entity which has a HasCompletedSecurity property which indicates whether that particular User has answered the number of security questions required by the system. The number of security questions the system requires is configurable and retrieved from a config file. How should the User class access the configured information?
I currently have an IConfigurationService interface behind which I have implementations which use the ConfigurationManager or the Azure equivalent if it is available. I've encapsulated access to my DI container through a static InjectionService class, and am currently resolving the configured value like so:
public class User
{
private static readonly IConfigurationService _configurationService =
InjectionService.Resolve<IConfigurationService>();
public bool HasCompletedSecurity
{
get
{
// Uses the static _configurationService to get the
// configured value:
int numberOfRequiredResponses =
GetConfiguredNumberOfRequiredResponses();
return this.SecurityQuestionResponses.Count()
>=
GetConfiguredNumberOfRequiredResponses();
}
}
}
This is of course an example of the ServiceLocator anti-pattern, and I don't like it one bit. The static dependency makes unit testing anything which uses this class awkward.
I'm using the Entity Framework and taking a cue from here I don't want to pass my entities through a DI container to give them their dependencies, so... how should I be accessing the configured value instead?
Edit: With this exact example to one side (and I do appreciate the suggestions as to the correct architecture for it), the larger question I'm interested in is how do you manage non-static references to services from entities? Is the answer to just architect the entities in such a way that you never need to?
Here's how I would define the User class:
public class User
{
public bool HasCompletedSecurity { get; set; }
// other members...
}
Seriously, this is a better solution because it decouples the value along the temporal dimension. Consider this: if a user completed all security questions in 2010 and you later on change the business rule, are you then going to invalidate the existing user?
In most cases it would probably be more reasonable to record and persist that sometime in the past, the user completed the security procedure that was in effect at that time. In that way, you don't bother existing users.
You can still using the concept of Inversion of Control without using any sort IoC container or requiring its use in the constructor of your entity. I would approach this using a quasi-strategy pattern and have something like:
public interface ISecurityPolicy
{
public int MinimumSecurityQuestionResponses { get; }
}
public class User
{
public void HasCompletedSecurity (ISecurityPolicy security_policy)
{
return this.SecurityQuestionResponses.Count()
>= security_policy.MinimumSecurityQuestionResponses;
}
}
This puts the onus of providing the particular security policy that the user must satisfy on the caller, not the User class itself.
From that point on, you can provide that extra parameter however you want to, maybe be wrapping this in a IUserSecurityService that will have the ISecurityPolicy injected into the service, etc.
This is still Inversion of Control, but it's at the method level, since this one particular method is really the only one that cares about the security policy/configuration.
I've came across a dilemma which I think is worth discussing here.
I have a set of domain objects (you can also call them entities, if you like), which get some data from a separate DAL which is resolved with an IoC.
I was thinking about making my system very extensible, and I'm wandering if it is right to also resolve these entities by the IoC.
Let me present a dumb example.
Let's say I have a web site for which I have the following interface:
public interface IArticleData
{
int ID { get; }
string Text { get; set; }
}
The concept is, that the DAL implements such interfaces, and also a generic IDataProvider<TData> inteface, after which the DAL becomes easily replaceable. And there is the following class, which uses it:
public class Article
{
private IArticleData Data { get; set; }
public int ID
{
get { return Data.ID; }
}
public int Text
{
get { return Data.Text; }
set { Data.Text = value; }
}
private Article(IArticleData data)
{
Data = data;
}
public static FindByID(int id)
{
IDataProvider<IArticleData> provider = IoC.Resolve<IDataProvider<IArticleData>>();
return new Article(provider.FindByID(id));
}
}
This makes the entire system independent of the actual DAL implementation (which would be in the example, IDataProvider<IArticleData>).
Then imagine a situation in which this functionality is not really enough, and I'd like to extend it. In the above example, I don't have any options to do it, but if I make it implement an interface:
public interface IArticle
{
int ID { get; }
string Text { get; set; }
}
public class Article : IArticle
{
...
}
And then, I remove all dependencies to the Article class and start resolving it as a transient IArticle component with an IoC.
For example, in Castle: <component id="ArticleEntity" service="IArticle" type="Article" lifestyle="transient" />
After this, if I have to extend it, that would be this simple:
public class MyArticle : Article
{
public string MyProperty { ..... }
}
And all I have to do is change the configuration to this: <component id="ArticleEntity" service="IArticle" type="Article" lifestyle="transient" />
So anyone who would use the system in question would be able to replace all classes as simply as rewriting a line in the configuration. All the other entities would work correctly also, because the new one would implement the same functionality as the old one.
By the way, this seems to be a good solution for the "separation of concerns" philosophy.
My question is, is this the right thing to do?
After some serious thinking, I couldn't figure out any better way to do this. I also considered MEF, but it seems to be oriented to making plugins but not to replace or extend already complete parts of a system like this.
I read many SO questions (and also other sources) about the topic, the most notable are these:
How should I handle my Entity/Domain Objects using IoC/Dependency Injection? and
IoC, Where do you put the container?
And I'm also afraid that I'm falling to the problems described on the following pages:
http://martinfowler.com/bliki/AnemicDomainModel.html and
http://hendryluk.wordpress.com/2008/05/10/should-domain-entity-be-managed-by-ioc/
And one more thing: this would increase the testability of the entire system, isn't it?
What do you think?
EDIT:
Another option would be to create a Factory pattern for these entities, but IoC.Resolve<IArticle> is way simpler than IoC.Resolve<IArticleFactory>().CreateInstance()
I think you may be overcomplicating things. Would you ever have a need to replace Article with another type that implemented IArticle?
IoC containers are best used when you have a higher-level component that depends on a lower-level component, and you want the higher-level component to depend on an abstraction of that component because the lower-level component performs some operations internally that make it difficult to test the higher-level component e.g. database access. Or the lower-level component might represent a particular strategy in your application that can be interchangeable with other strategies e.g. a database gateway that abstracts out the details of working with vendor-specific database APIs.
As Article is a simple, POCO-style class, it's unlikely that you would gain any benefits creating instances of it though an IoC container.