Separating the service layer from the validation layer - c#

I currently have a service layer based on the article Validating with a service layer from the ASP.NET site.
According to this answer, this is a bad approach because the service logic is mixed with the validation logic which violates the single responsibility principle.
I really like the alternative that is supplied but during re-factoring of my code I have come across a problem that I am unable to solve.
Consider the following service interface:
interface IPurchaseOrderService
{
void CreatePurchaseOrder(string partNumber, string supplierName);
}
with the following concrete implementation based on the linked answer:
public class PurchaseOrderService : IPurchaseOrderService
{
public void CreatePurchaseOrder(string partNumber, string supplierName)
{
var po = new PurchaseOrder
{
Part = PartsRepository.FirstOrDefault(p => p.Number == partNumber),
Supplier = SupplierRepository.FirstOrDefault(p => p.Name == supplierName),
// Other properties omitted for brevity...
};
validationProvider.Validate(po);
purchaseOrderRepository.Add(po);
unitOfWork.Savechanges();
}
}
The PurchaseOrder object that is passed to the validator also requires two other entities, Part and Supplier (let's assume for this example that a PO only has a single part).
Both the Part and Supplier objects could be null if the details supplied by the user do not correspond to entities in the database which would require the validator to throw an exception.
The problem I have is that at this stage the validator has lost the contextual information (the part number and the supplier name) so is unable to report an accurate error to the user. The best error I can supply is along the lines of "A purchase order must have an associated part" which would not make sense to the user because they did supply a part number (it just does not exist in the database).
Using the service class from the ASP.NET article I am doing something like this:
public void CreatePurchaseOrder(string partNumber, string supplierName)
{
var part = PartsRepository.FirstOrDefault(p => p.Number == partNumber);
if (part == null)
{
validationDictionary.AddError("",
string.Format("Part number {0} does not exist.", partNumber);
}
var supplier = SupplierRepository.FirstOrDefault(p => p.Name == supplierName);
if (supplier == null)
{
validationDictionary.AddError("",
string.Format("Supplier named {0} does not exist.", supplierName);
}
var po = new PurchaseOrder
{
Part = part,
Supplier = supplier,
};
purchaseOrderRepository.Add(po);
unitOfWork.Savechanges();
}
This allows me to provide much better validation information to the user but means that the validation logic is contained directly in the service class, violating the single responsibility principle (code is also duplicated between service classes).
Is there a way of getting the best of both worlds? Can I separate the service layer from the validation layer whilst still providing the same level of error information?

Short answer:
You are validating the wrong thing.
Very long answer:
You are trying to validate a PurchaseOrder but that is an implementation detail. Instead what you should validate is the operation itself, in this case the partNumber and supplierName parameters.
Validating those two parameters by themselves would be awkward, but this is caused by your design—you're missing an abstraction.
Long story short, the problem is with your IPurchaseOrderService interface. It shouldn't take two string arguments, but rather one single argument (a Parameter Object). Let's call this Parameter Object CreatePurchaseOrder:
public class CreatePurchaseOrder
{
public string PartNumber;
public string SupplierName;
}
With the altered IPurchaseOrderService interface:
interface IPurchaseOrderService
{
void CreatePurchaseOrder(CreatePurchaseOrder command);
}
The CreatePurchaseOrder Parameter Object wraps the original arguments. This Parameter Object is a message that describes the intend of the creation of a purchase order. In other words: it's a command.
Using this command, you can create an IValidator<CreatePurchaseOrder> implementation that can do all the proper validations including checking the existence of the proper parts supplier and reporting user friendly error messages.
But why is the IPurchaseOrderService responsible for the validation? Validation is a cross-cutting concern and you should prevent mixing it with business logic. Instead you could define a decorator for this:
public class ValidationPurchaseOrderServiceDecorator : IPurchaseOrderService
{
private readonly IValidator<CreatePurchaseOrder> validator;
private readonly IPurchaseOrderService decoratee;
ValidationPurchaseOrderServiceDecorator(
IValidator<CreatePurchaseOrder> validator,
IPurchaseOrderService decoratee)
{
this.validator = validator;
this.decoratee = decoratee;
}
public void CreatePurchaseOrder(CreatePurchaseOrder command)
{
this.validator.Validate(command);
this.decoratee.CreatePurchaseOrder(command);
}
}
This way you can add validation by simply wrapping a real PurchaseOrderService:
var service =
new ValidationPurchaseOrderServiceDecorator(
new CreatePurchaseOrderValidator(),
new PurchaseOrderService());
Problem, of course, with this approach is that it would be really awkward to define such decorator class for each service in the system. That would cause severe code publication.
But the problem is caused by a flaw. Defining an interface per specific service (such as the IPurchaseOrderService) is typically problematic. You defined the CreatePurchaseOrder and, therefore, already have such a definition. You can now define one single abstraction for all business operations in the system:
public interface ICommandHandler<TCommand>
{
void Handle(TCommand command);
}
With this abstraction you can now refactor PurchaseOrderService to the following:
public class CreatePurchaseOrderHandler : ICommandHandler<CreatePurchaseOrder>
{
public void Handle(CreatePurchaseOrder command)
{
var po = new PurchaseOrder
{
Part = ...,
Supplier = ...,
};
unitOfWork.Savechanges();
}
}
With this design, you can now define one single generic decorator to handle all validations for every business operation in the system:
public class ValidationCommandHandlerDecorator<T> : ICommandHandler<T>
{
private readonly IValidator<T> validator;
private readonly ICommandHandler<T> decoratee;
ValidationCommandHandlerDecorator(
IValidator<T> validator, ICommandHandler<T> decoratee)
{
this.validator = validator;
this.decoratee = decoratee;
}
void Handle(T command)
{
var errors = this.validator.Validate(command).ToArray();
if (errors.Any())
{
throw new ValidationException(errors);
}
this.decoratee.Handle(command);
}
}
Notice how this decorator is almost the same as the previously defined ValidationPurchaseOrderServiceDecorator, but now as a generic class. This decorator can be wrapped around your new service class:
var service =
new ValidationCommandHandlerDecorator<PurchaseOrderCommand>(
new CreatePurchaseOrderValidator(),
new CreatePurchaseOrderHandler());
But since this decorator is generic, you can wrap it around every command handler in your system. Wow! How's that for being DRY?
This design also makes it really easy to add cross-cutting concerns later on. For instance, your service currently seems responsible for calling SaveChanges on the unit of work. This can be considered a cross-cutting concern as well and can easily be extracted to a decorator. This way your service classes become much simpler with less code left to test.
The CreatePurchaseOrder validator could look as follows:
public sealed class CreatePurchaseOrderValidator : IValidator<CreatePurchaseOrder>
{
private readonly IRepository<Part> partsRepository;
private readonly IRepository<Supplier> supplierRepository;
public CreatePurchaseOrderValidator(
IRepository<Part> partsRepository,
IRepository<Supplier> supplierRepository)
{
this.partsRepository = partsRepository;
this.supplierRepository = supplierRepository;
}
protected override IEnumerable<ValidationResult> Validate(
CreatePurchaseOrder command)
{
var part = this.partsRepository.GetByNumber(command.PartNumber);
if (part == null)
{
yield return new ValidationResult("Part Number",
$"Part number {command.PartNumber} does not exist.");
}
var supplier = this.supplierRepository.GetByName(command.SupplierName);
if (supplier == null)
{
yield return new ValidationResult("Supplier Name",
$"Supplier named {command.SupplierName} does not exist.");
}
}
}
And your command handler like this:
public class CreatePurchaseOrderHandler : ICommandHandler<CreatePurchaseOrder>
{
private readonly IUnitOfWork uow;
public CreatePurchaseOrderHandler(IUnitOfWork uow)
{
this.uow = uow;
}
public void Handle(CreatePurchaseOrder command)
{
var order = new PurchaseOrder
{
Part = this.uow.Parts.Get(p => p.Number == partNumber),
Supplier = this.uow.Suppliers.Get(p => p.Name == supplierName),
// Other properties omitted for brevity...
};
this.uow.PurchaseOrders.Add(order);
}
}
Note that command messages will become part of your domain. There is a one-to-one mapping between use cases and commands and instead of validating entities, those entities will be an implementation detail. The commands become the contract and will get validation.
Note that it will probably make your life much easier if your commands contain as much IDs as possible. So your system would could benefit from defining a command as follows:
public class CreatePurchaseOrder
{
public int PartId;
public int SupplierId;
}
When you do this you won't have to check if a part by the given name does exist. The presentation layer (or an external system) passed you an ID, so you don't have to validate the existence of that part anymore. The command handler should of course fail when there's no part by that ID, but in that case there is either a programming error or a concurrency conflict. In either case no need to communicate expressive user friendly validation errors back to the client.
This does, however, moves the problem of getting the right IDs to the presentation layer. In the presentation layer, the user will have to select a part from a list for us to get the ID of that part. But still I experienced the this to make the system much easier and scalable.
It also solves most of the problems that are stated in the comments section of the article you are referring to, such as:
The problem with entity serialization goes away, because commands can be easily serialized and model bind.
DataAnnotation attributes can be applied easily to commands and this enables client side (Javascript) validation.
A decorator can be applied to all command handlers that wraps the complete operation in a database transaction.
It removes the circular reference between the controller and the service layer (via the controller's ModelState), removing the need for the controller to new the service class.
If you want to learn more about this type of design, you should absolutely check out this article.

Related

How to write unit tests for proxy pattern?

Will be thankful for your attention, time and efforts !
I have the following code
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Role { get; set; }
}
public interface IEmployeeRepository
{
Employee GetEmployee(string firstName, string role);
}
public class EmployeeRepository : IEmployeeRepository
{
public Employee GetEmployee(string firstName, string role)
{
//logic here
return new Employee();
}
}
Now i want to implement cache for EmployeeRepository.
At first i did it using Proxy design pattern
public class ProxyEmployeeRepository : IEmployeeRepository
{
private EmployeeRepository _employeeRepository = new EmployeeRepository();
private MemoryCache _cache = new MemoryCache("UsualCache");
public Employee GetEmployee(string firstName, string role)
{
//do not cache administrators
if (role == "admin")
{
return _employeeRepository.GetEmployee(firstName, role);
}
else
{
//get from cache at first
//if absent call _employeeRepository.GetEmployee and add to cache
//...
}
}
But when wanted to write unit tests for this class i couldn't do it(i cannot create mock for _employeeRepository and verify whether it was called or not)
If i implement cache with Decorator pattern then i would have the following code
public class DecoratorEmployeeRepository : IEmployeeRepository
{
private IEmployeeRepository _employeeRepository;
public DecoratorEmployeeRepository(IEmployeeRepository repository)
{
_employeeRepository = repository;
}
private MemoryCache _cache = new MemoryCache("UsualCache");
public Employee GetEmployee(string firstName, string role)
{
//do not cache administrators
if (role == "admin")
{
return _employeeRepository.GetEmployee(firstName, role);
}
else
{
//get from cache at first
//if absent call _employeeRepository.GetEmployee and add to cache
return null;
}
}
}
and unit tests for it
[TestClass]
public class EmployeeRepositoryTests
{
[TestMethod]
public void GetEmployeeTest_AdminRole()
{
var innerMock = Substitute.For<IEmployeeRepository>();
var employeeRepository = new DecoratorEmployeeRepository(innerMock);
employeeRepository.GetEmployee("Ihor", "admin");
innerMock.Received().GetEmployee(Arg.Any<string>(), Arg.Any<string>());
}
[TestMethod]
public void GetEmployeeTest_NotAdminRole()
{
var innerMock = Substitute.For<IEmployeeRepository>();
var employeeRepository = new DecoratorEmployeeRepository(innerMock);
employeeRepository.GetEmployee("Ihor", "NotAdmin");
innerMock.DidNotReceive().GetEmployee("Ihor", "NotAdmin");
}
}
Is it possible to write unit tests for first approach with proxy pattern ? i just don't understand how it is possible to cover proxy class with unit tests ...
I know it is too late to answer your question but it might help other new visitors:
I think your problem is your misunderstanding of both patterns. By using composition instead of instantiating your class inside the proxy, does not necessarily mean that you have changed your pattern from proxy to decorator. Each of these patterns is solving a specific problem. Let me clarify each:
Decorator Pattern:
This pattern is useful when you have different kinds of behaviours in your main class (like caching, logging, lazy loading and etc.) and you want to use each of these or a combination of them in different places of your application. For example, in your controller, you need only caching, in the admin controller you don't need caching but logging and in another service, you need both plus lazy loading. Therefore you will create three decorators for each extra behaviour (caching, logging and lazy loading) and in each place, you link the decorators into each other to provide various kinds of behaviours. The benefit of this pattern is that each class has only one responsibility. Additionally, your application is open to extension and close to modification. If you need a new behaviour, you can simply implement a new decorator from the interface and add it only to the services or controllers that the new behaviour is required without modifying the current implementation.
Proxy Pattern:
This pattern is useful when you want to add specific behaviour or behaviours that are required for your class but can prevent the actual behaviour (querying the database) and/or new behaviours come into the picture (which is not the behaviour in the decorator pattern. It only enhances the main behaviour). Another usage of this pattern is when instantiating the main class is costly. So in contrast, you do not need each behaviour (or various combination of them) separately in several places of your application.
The benefit of this pattern is that it prevents adding several responsibilities to your main class. Besides, it is still close to modification and open to extension. If the requirements change in future, you can simply implement a new proxy and replace it with the correct one or use it separately.
The answer to your question:
Therefore, as I mentioned above, by having a composition to your interface instead of instantiating it directly, you are not changing the pattern. In proxy pattern, the main class can be injected via the interface or the concrete implementation as well.

reusing services calls in unit of work pattern

I have a scenario using WebApi, Generic Repository, EF6 and unit of work pattern
(in order to wrap all changes from several calls to the same context.)
Manager layer is used to perform calls to different repositories and also to other managers.
Currently Customer Manager does inject both repos and other Managers like:
public class CustomerManager {
public CustomerManager(IRepository<Customer> _customerRepository, IRepository<Order> orderRepository, IManager itemManager) {
_orderReporsitory = orderReporsitory;
_itemManager = itemManager;
_customerRepository = customerRepository;
}
public bool Save(Customer customer) {
_orderReporsitory.Find...
_itemManager.IsItemUnique(ItemId)
_customerRepository.Save(customer);
}
}
This code does not compile, for reference only.
Approaches like this
http://blog.longle.net/2013/05/11/genericizing-the-unit-of-work-pattern-repository-pattern-with-entity-framework-in-mvc/
Will wrap several repositories under a unit of work and flush the changes all together.
My issue involves also adding another Manager layer, to be wrapped also inside unit of work and allow both calls to repositories and other managers
(as I want to reuse some manager logic. Like in the example, I am re-using some ItemManager logic)
This code https://stackoverflow.com/a/15527444/310107
using (var uow = new UnitOfWork<CompanyContext>())
{
var catService = new Services.CategoryService(uow);
var custService = new Services.CustomerService(uow);
var cat = new Model.Category { Name = catName };
catService.Add(dep);
custService.Add(new Model.Customer { Name = custName, Category = cat });
uow.Save();
}
is using something similar of what I need but I would also like to be able to inject the services to unit test them (and not creating instances in the body of my manager/service method)
What would the best approach to do this ?
Thanks
Your code snippet with the unit of work has several problems, such as:
You create and dispose the unit of work explicitly within that method, forcing you to pass along that unit of work from method to method and class to class.
This causes you to violate the Dependency Inversion Principle, because you now depend on concrete types (CategoryService and CustomerService), which complicates your code and makes your code harder to test.
If you need to change the way the unit of work is created, managed or disposed, you will have to make sweeping changes throughout the application; A violation of the Open/Closed Principle.
I expressed these problems in more details in this answer.
Instead, I propose to have one DbContext, share it through a complete request, and control its lifetime in the application's infrastructure, instead of explicitly throughout the code base.
A very effective way of doing this is by placing your service layer behind a generic abstaction. Although the name of this abstraction is irrelevant, I usually call this abstraction 'command handler:
public interface ICommandHandler<TCommand>
{
void Handle(TCommand command);
}
There are a few interesting things about this abstaction:
The abstraction describes one service operation or use case.
Any arguments the operation might have are wrapped in a single message (the command).
Each operation gets its own unique command class.
Your CustomerManager for instance, might look as follows:
[Permission(Permissions.ManageCustomerDetails)]
public class UpdateCustomerDetailsCommand {
public Guid CustomerId { get; set; }
[Required] public string FirstName { get; set; }
[Required] public string LastName { get; set; }
[ValidBirthDate] public DateTime DateOfBirth { get; set; }
}
public class UpdateCustomerDetailsCommandHandler
: ICommandHandler<UpdateCustomerDetailsCommand> {
public UpdateCustomerDetailsCommandHandler(
IRepository<Customer> _customerRepository,
IRepository<Order> orderRepository,
IManager itemManager) {
_orderReporsitory = orderReporsitory;
_itemManager = itemManager;
_customerRepository = customerRepository;
}
public void Handle(UpdateCustomerDetailsCommand command) {
var customer = _customerRepository.GetById(command.CustomerId);
customer.FirstName = command.FirstName;
customer.LastName = command.LastName;
customer.DateOfBirth = command.DateOfBirth;
}
}
This might look like just a bunch of extra code, but having this message and this generic abstraction allows us to easily apply cross-cutting concerns, such as handling the unit of work for instance:
public class CommitUnitOfWorkCommandHandlerDecorator<TCommand>
: ICommandHandler<TCommand> {
private readonly IUnitOfWork unitOfWork;
private readonly ICommandHandler<TCommand> decoratee;
public CommitUnitOfWorkCommandHandlerDecorator(
IUnitOfWork unitOfWork,
ICommandHandler<TCommand> decoratee) {
this.unitOfWork = unitOfWork;
this.decoratee = decoratee;
}
public void Handle(TCommand command) {
this.decoratee.Handle(command);
this.unitOfWork.SaveChanges();
}
}
The class above is a decorator: It both implements ICommandHandler<TCommand> and it wraps ICommandHandler<TCommand>. This allows you to wrap an instance of this decorator around each command handler implementation and allow the system to transparently save the changes made in the unit of work, without any piece of code having to do this explicitly.
It is also possible to create a new unit of work here, but the easiest thing to start with is to let the unit of work live for the duration of the (web) request.
This decorator will however just be the beginning of what you can do with decorators. For instance, it will be trivial to:
Apply security checks
Do user input validation
Run the operation in a transaction
Apply a deadlock retry mechanism.
Prevent reposts by doing deduplication.
Register each operation in an audit trail.
Store commands for queuing or background processing.
More information can be found in the articles, here, here and here.

Domain model validation, inheritance and testability

The Situation
I'm building a C# web application and I want to model my app configuration as an explicit dependency to be handed in through the constructor of a service instead of relying on System.Configuration.ConfigurationManager directly in each of the classes. This did bite my quite often in the past so I want the dependency to be explicit so that the next maintainer of the project (probably future me) doesn't have to guess where my services get their configuration settings - on top of that it is more TDD friendly. Furthermore I'm currently reading Eric Evan's Domain Driven Design and I really want to embrace his DDD approach.
I started modeling the configuration class and corresponding value objects to avoid Primitive Obsession but I hit some bumps on the way and I'm not sure how to handle them appropriately. Here is my current approach:
// Role interface that can be requested via constructor injection
interface IAppConnectionStringsConfig
{
OleDbConnectionString AuthenticationConnectionString { get; }
}
// A base class for handling common functionality like
// parsing comma separated lists or default values
class abstract AppConfigBase
{
protected string GetStringAppSetting(string key)
{
// Get the appropriate string or a default value from
// System.Configuration.ConfigurationManager
return theSettingFromSomeConfigSource;
}
}
// A value object for OLEDB connection strings that also has a
// convenient implicit conversion to string
class OleDbConnectionString
{
public readonly string Value;
public OleDbConnectionString(string connectionString)
{
Contract.Requires(connectionString != null);
this.VerifyStructure(connectionString);
this.Value = connectionString;
}
private void VerifyStructure(string text)
{
Contract.Requires(text != null);
// Verify that the given string fulfills the special
// needs of an OleDbConnectionString (including Provider=...)
if (!/* isValidOleDbConnectionString */)
{
throw new FormatException();
}
}
public implicit operator string(ConnectionString conn)
{
return conn.Value;
}
}
// The actual app config that implements our role interface
class AppConfig : AppConfigBase, IAppConnectionStringsConfig
{
public OleDbConnectionString AuthenticationConnectionString
{
get
{
return new OleDbConnectionString(this.GetStringAppSetting("authconn"));
}
}
}
The Problem
I know that constructor logic should be minimal and that is not a good idea to call virtual methods from the constructor. My questions are as follows:
1) Where should I put the validation logic for the OleDbConnectionString? I really want to prevent the creation of value objects in an invalid state - that's excrutiatingly usefull at a day to day basis :-)
I have the feeling that this is domain logic that should be owned by the class itself but on the other hand the constructor should do as little as possible - wouldn't the string parsing be too much or is this ok?
I could create a validator but I most certainly had to hand that in through the constructor for being able to test that thing properly and then I have to wire that manually or use a factory (I'm definitely not using a Service Locator). On top of that the validation now would be hidden in a separate service; I wouldn't have the temporal coupling since the constructor requires the validator but still that doesn't look right.
2) I wonder if it would be appropriate to make DDD value objects structs? They - like the name suggests - represent a single value and this value is immutable. But they would contain business logic in the form of validation
3) Is it OK to use a property for retrieving the connection string? It could throw an exception if the format for the string isn't valid. Furthermore it's perfectly possible that the implementation will be changed from reading from an xml config file to querying a database.
4) Any other comments on the design are welcome!
As a side note, I'm already using Code Contracts and there is a way to specify object invariants but I don't know whether this is really a good idea since these contracts are opt-in and in the case that they are inactive the invariants are no longer actively protected. I'm not sure about this, for development purposes to catch errors early it might be fine but for production it seems off.
Thx!
I never really thought about general settings as a DDD problem - are you modelling a domain that is about settings and how they are saved, or just allowing settings to be saved and used in an application that has some inner parts modeled as DDD?
You can split this out by separating concerns of getting settings away from the things that use the settings.
Is it OK to use a property for retrieving the connection string? It could throw an exception if the format for the string isn't valid.
I don't think its a good idea to throw an exception if a setting cannot be retrieved so you can return defaults which would allow the program to continue.
But also remember that the default returned value (i.e. a password, or network address) will probably cause the thing that depends on that setting to throw an exception.
I would look at allowing the construction to happen OK but when coming to use the service i.e. Sender.Send() or Sender.Connect() is when you would throw an exception.
Where should I put the validation logic for the OleDbConnectionString? I really want to prevent the creation of value objects in an invalid state
I create objects that can never return an invalid result, but they do return a default settings value:
public class ApplicationSettings : IIdentityAppSettings, IEventStoreSettings
{
/* snip */
static readonly object KeyLock = new object();
public byte[] StsSigningKey
{
get
{
byte[] key = null;
lock (KeyLock)
{
var configManager = WebConfigurationManager.OpenWebConfiguration("/");
var configElement = configManager.AppSettings.Settings["StsSigningKey"];
if (configElement == null)
{
key = CryptoRandom.CreateRandomKey(32);
configManager.AppSettings.Settings.Add("StsSigningKey", Convert.ToBase64String(key));
configManager.Save(ConfigurationSaveMode.Modified); // save to config file
}
else
{
key = Convert.FromBase64String(configElement.Value);
}
}
return key;
}
/* snip */
}
}
What I generally do
I have the settings interfaces for each bounded context defined in the domain model as part of the infrastructure - this allows a number of known interfaces which I can reference and trust to provide some form of settings.
ApplicationSettings is defined in the code that hosts my bounded context(s) be it a Console app or WebAPI or MVC etc, I may have multiple bounded contexts hosted under the same process, or may split them out as separate processes, either way it is the job of the hosting application to provide the relevant application settings and wiring can be done via the IoC container.
public class ApplicationSettings : IIdentityAppSettings, IEventStoreSettings
{
// implement interfaces here
}
public interface IEventStoreSettings
{
string EventStoreUsername { get; }
string EventStorePassword { get; }
string EventStoreAddress { get; }
int EventStorePort { get; }
}
public interface IIdentityAppSettings
{
byte[] StsSigningKey { get; }
}
I use SimpleInjector .NET IoC container to wire up my applications. I then register all the application interfaces with SimpleInjector (so i can query based on any of the application interfaces and have the settings class object returned):
resolver.RegisterAsImplementedInterfaces<ApplicationSettings>();
I can then have the specific interface injected in, an example is a command handler that uses an IRepository, which in turn the EventStoreRepository (which is wired up as an implementation of IRepository) uses IEventStoreSettings (which is wired up as the ApplicationSettings instance):
public class HandleUserStats : ICommandHandler<UserStats>
{
protected IRepository repository;
public HandleUserStats(IRepository repository)
{
this.repository = repository;
}
public void Handle(UserStats stats)
{
// do something
}
}
And my repository would in turn be wired up:
public class EventStoreRepository : IRepository
{
IEventStoreSettings eventStoreSettings;
public EventStoreRepository(IEventStoreSettings eventStoreSettings)
{
this.eventStoreSettings = eventStoreSettings;
}
public void Write(object obj)
{
// just some mockup code to show how to access setting
var eventStoreClient = new EventStoreClient(
this.eventStoreSettings.EventStoreUsername,
this.eventStoreSettings.EventStorePassword,
this.eventStoreSettings.EventStoreAddress,
this.eventStoreSettings.Port
);
// if ever there was an exception either during setup of the connection, or
// exception (if you don't return a default value) accessing settings, it
// could be caught and bubbled up as an InfrastructureException
// now do something with the event store! ....
}
}
I allow settings to be passed in from some external source (like a WCF receive, or MVC controller action) and wired up by getting resolver.GetInstance<CommandHandler<UserStats>>(); which wires up all the settings for me all the way down to the implementation level.

Where should the validation go in CQRS with MVC?

This is my post method for creating a new user:
[HttpPost]
public ActionResult CreateUser(CreateUserViewModel createUserViewModel)
{
CreateSystemUserCommand createSystemUserCommand = new CreateSystemUserCommand()
{
Firstname = createUserViewModel.Forename,
Surname = createUserViewModel.Surname,
Username = createUserViewModel.Username,
Password = createUserViewModel.Password
};
CreateSystemUserCommandHandler handler = new CreateSystemUserCommandHandler();
handler.Execute(createSystemUserCommand);
return RedirectToAction("ViewUsers");
}
There is some validation on the view model already, required fields etc. so the UI will have validation on it.
However I'm wondering how to do it server side.
Should I create a method createSystemUserCommand.Validate();
or before handler.Execute(), do handler.Validate()?
And how should I translate those errors into the ModelState? I'm guessing CQRS is not connected with MVC therefore it'd make no sense to return specifically model errors.
Any thoughts welcome on this. My gut feeling is to do handler.Validate since it'll keep validation logic within a single class, and it feels right, but I am open to suggestions.
There are 2 types of validation here that you could potentially need:
One is simple ModelState validation which ensures that required fields are not missing, int is an int and so on. For that, using Data annotation attributes will do the trick.
The second type is business logic validation - something that may require accessing database or running some other validation logic to make sure that data integrity is not affected. That type of validation would be at the command level.
The best way to do that is to follow the decorator pattern - wrap your actual handler in a validating handler:
public class ValidationCommandHandlerDecorator<TCommand, TResult>
: ICommandHandler<TCommand, TResult>
where TCommand : ICommand<TResult>
{
private readonly ICommandHandler<TCommand, TResult> decorated;
public ValidationCommandHandlerDecorator(ICommandHandler<TCommand, TResult> decorated)
{
this.decorated = decorated;
}
[DebuggerStepThrough]
public TResult Handle(TCommand command)
{
var validationContext = new ValidationContext(command, null, null);
Validator.ValidateObject(command, validationContext, validateAllProperties: true);
return this.decorated.Handle(command);
}
}
An example of validator would be:
public class SomeCustomLogicValidator : IValidator {
void IValidator.ValidateObject(object instance) {
var context = new ValidationContext(instance, null, null);
// Throws an exception when instance is invalid.
Validator.ValidateObject(instance, context, validateAllProperties: true);
}
}
And then register it as:
// using SimpleInjector.Extensions;
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(ValidationCommandHandlerDecorator<>));
You can wrap as many decorators as you wish or even make it specific to a predicate (exact syntax depends on what DI framework you use):
// another decorator
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(TransactionCommandHandlerDecorator<>));
// specific decorator
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(AccessValidationCommandHandlerDecorator<>),
context => !context.ImplementationType.Namespace.EndsWith("Admins"));
The example I have uses a DI framework which makes things simpler, but this idea can be extended without using any DI container as well.
I typically use FluentValidation in my application layer (like in the command handlers) and in domain layer. These validators all throw exceptions, which I catch in a global exception handler, which has the responsability to propagate them to the consumer in the correct format (for example as a fault in WCF). These messages are already in the correct language, based on the culture that was set on the thread (if you have multi lingual site).
On the site, the list of errors is then used. The error messages are simply displayed and based on the error keys I can add additional logic to disable controls etc.
So in my case validation is in most cases server side and only defined once in application and domain layer. On client side there can be some other small input validation, to restrict user input for example.
I'm not sure if you are using Data Annotations or not, but with Data Annotations it can be like this.
Also see additional attribute ValidateAntiForgeryToken (may be useful for you).
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateUser(CreateUserViewModel createUserViewModel)
{
if (ModelState.IsValid)
{
CreateSystemUserCommand createSystemUserCommand = new CreateSystemUserCommand()
{
Firstname = createUserViewModel.Forename,
Surname = createUserViewModel.Surname,
Username = createUserViewModel.Username,
Password = createUserViewModel.Password
};
CreateSystemUserCommandHandler handler = new CreateSystemUserCommandHandler();
handler.Execute(createSystemUserCommand);
return RedirectToAction("ViewUsers");
}
return View(createUserViewModel);
}
But if you need complex validation you can go with:
if (ModelState.IsValid && handler.Validate())
Or you can implement you own validation logic and then add errors to ModelState by using ModelState.AddModelError.

Entity repsoitory/service pattern, where to put functionality that needs 2 or more services

I have created a generic repository for my entity types which handles retrieving , adding and deleting data. Each entity type has a corresponding Service class which interacts with the generic repository to handle all the Data access.
However many times i need to retrieve data based on more than one service and i am never sure where to place this code. For example below is some code that returns a list of email addresses ("GetEmailTrackingAddressGroup" function) which is using 3 different service. I have placed this in the "GroupService" but it could also easily go in the "UserService" aswell.
public class GroupService
{
IRepository<Group> groupRepository;
public GroupService(IRepository<Group> groupRepository)
{
this.groupRepository = groupRepository;
}
public Group GetById(int id)
{
return groupRepository.GetSingle(g => g.Id == id);
}
public static List<string> GetEmailTrackingAddressesGroup(int instanceId, int groupId)
{
MyEntities entityContext = new MyEntities();
UserGroupService userGroupService =
new UserGroupService(new BaseRepoistory<UserGroup>(entityContext ));
UserService userService =
new UserService(new BaseRepoistory<User>(entityContext ));
List<string> emails = new List<string>();
Group productGroup = GetById(groupId);
foreach (UserGroup userGroup in userGroupService.GetByGroupId(productGroup.Id))
{
if (userGroup.EmailTracking)
emails.Add(userService.GetByUserId(userGroup.UserId).UserName);
}
return emails;
}
}
My Question is, should you just try and pick the most relevant service and place the code in there and call the other relevant service inside it, or should i create a new class which handles Data access when more than 1 service is involved. For example i have placed code for what this class might look like below.
public class DataFunctions
{
public static List<string> GetEmailTrackingAddressesGroup(int instanceId, int groupId)
{
MyEntities entityContext = new MyEntities();
GroupService userGroupService =
new GroupService(new BaseRepoistory<Group>(entityContext ));
UserGroupService userGroupService =
new UserGroupService(new BaseRepoistory<UserGroup>(entityContext ));
UserService userService =
new UserService(new BaseRepoistory<User>(entityContext ));
List<string> emails = new List<string>();
Group productGroup = GetById(groupId);
foreach (UserGroup userGroup in userGroupService.GetByGroupId(productGroup.Id))
{
if (userGroup.EmailTracking)
emails.Add(userService.GetByUserId(userGroup.UserId).UserName);
}
return emails;
}
}
The second approach seems to make more sense as this means each service will never rely on other services however im not sure if i am going about this the right way. One concern i have about using this separate class is that it will get very big and hard to manage.
Edit - For now i have come up with a third solution, i think it is better than my previous two however i'm still uncertain if i am managing this correctly. I have created a seperate "EmailService" which will handle all data queries which are needed when handing email functionality in my main ASP.Net web project.
Below is the code for this new class
//Functionality realting to data needed when handling emails
public class EmailService
{
MyEntities entityContext;
AspUserService aspUserService;
GroupService groupService;
UserGroupService userGroupService;
public EmailService()
{
entityContext = new MyEntities ();
aspUserService = new AspUserService(new RepositoryBase<aspnet_Users>(entityContext));
groupService = new GroupService(new RepositoryBase<Group>(entityContext));
userGroupService = new UserGroupService(new RepositoryBase<UserGroup>(entityContext));
}
public List<string> GetEmailsForProductGroup(int groupId)
{
List<string> emails = new List<string>();
Group productGroup = groupService.GetById(groupId);
foreach (UserGroup userGroup in userGroupService.GetByGroupId(productGroup.Id))
{
if (userGroup.EmailTracking)
emails.Add(aspUserService.GetByUserId(userGroup.UserId).UserName);
}
return emails;
}
}
If you were to do maintenance on an application you've never seen before, where would you expect it to be? Since it is something that "belongs" to a group, i think that putting it in the group-repo/service would be the right approach. In your example, i would suggest creating a new group-repository, extending the IRepository of group, and create a method for getting the group object, including the connection entities. When scaling your application, this will make a huge difference, since you wont have to query the database for every subobject (n+1 problem).
No offense, but all your approaches suck for the following reasons: tight coupling and messing around responsibilities.
The generic repository is an anti pattern, stay away from it. Your first approach pretty much does the work of a repository and it's a static function (why?!).
The services shouldn't be coupled to concrete repositories. All dependencies should be injected as abstractions via constructor. I get the feeling that aspUsersService,GroupService and UserGroupService (what's the difference????) are actually implemented like a repository and thus, they are useless.
Actually from what I see, all your services are practically repositories. Cut the useless code, have one service/repository that uses directly EF and that's it.
It looks like you're a little confused between the point of repositories and service classes. Your service classes are just repositories. You ended up having to work this way because of the generic repository pattern. This pattern is actually an anti-pattern. It seems nice at first until you get to the point you're at. Instead you should create repositories for each of your entities that handle all CRUD operations for that entity. In these repositories is where you'll place your 'GetEmailTrackingAddressesGroup' type methods. And then your service layer can handle interacting with more that one repository if need be. Your service classes shouldn't have hard coded instances of your repositories. Instead you should be inject repository interfaces into your service's constructor.
Here's an example of how I would set up repositories and a simple service that interacts with 2 repositories.
public interface IUserRepository
{
void Insert(User user);
...
IEnumerable<User> GetByDepartmentId(int deptId);
}
public interface IContactLogRepository
{
void Insert(ContactLog contactLog);
}
public class EmailService
{
private readonly IUserRepository _userRepo;
private readonly IContactLogRepository _contactLogRepo;
public EmailService(IUserRepository userRepo, IContactLogRepository contLogRepo) {
_userRepo = userRepo;
_contactLogRepo = contLogRepo;
}
public void EmailDepartment(int deptId, string message) {
var employees = _userRepo.GetByDepartmentId(deptId);
foreach (var emp in employees) {
Email(emp.Email, message);
_contactLogRepo.Insert(new ContactLog {
EmployeeId = emp.Id,
Message = message
});
}
}
private void Email(string address, string message) {
...
}
}
So our repositories are there to handle CRUD operations for a specific entity - not our service layer. The generic repository pattern forces us to do CRUD (well at least the retrieval) in our services.

Categories

Resources