I am currently at the beginning of developing a large web application mainly containing an Angular SPA and an OData WebAPI that has access to a backend layer.
We're at an early stage and have begun to implement the first classes including a Model.dll that is in a common namespace so that it can be accessed by all layers.
We are now discussing about those DTOs within the model. Some say that using interfaces is absolutely neccessary, so the code would be like this:
namespace MySolution.Common.Model
{
public interface IPerson
{
int Id { get; set; }
string Name { get; set; }
...
}
}
namespace MySolution.Common.Model
{
public class PersonDTO : IPerson
{
public int Id { get; set; }
public string Name { get; set; }
...
}
}
So that's it. Just simple DTOs with no more intelligence.
I am now asking myself if this is really a good approach, because I don't see the necessity of using the interface here.
What are the advantages with this? Testability was mentioned, but is it even necessary to test DTos? Dependency Injection should also not the point.
Any enlightenment would be very helpful. At the end learning new stuff and approaches is always good...
DTOs transfer state - that's it. Injecting them via a container or mocking them for testing seems pointless (if that's the motivation) and totally unnecessary. Don't do it.
As an example, further to my comment above:
Interface IRepo
{
Person GetPerson(int id);
}
Public class DbRepo : IRepo
{
public Person GetPerson(int id){//get person from database}
}
Public class FakeRepo : IRepo
{
public Person GetPerson(int id)
{
return new Person {Id = id, Name = "TestName"};
}
}
You would use a FakeRepo with some mock objects for testing purposes.
I have this situation, where i'm writing a api that should be loosely coupled, because I can adapt any of its parts to behave different, like changing the storage, or alter a number of parameter from a request, so it can have another behavior without affecting what already exist.
With this in mind, is valid have a interface for the DTO, because on another time it could change its properties to carry more data, and you have only to implement a abstraction where you will use this new implemented dto, be to map the new parameters, use in a service to register a record.
Then you do the bindings of the interface(abstraction) to new implementations of the dto and the places that will have modifications.
Then you don't change the behavior of you program and don't make alterations on what already exist.
So you have to think too how will be you api.
DTOs may inherit properties from multiple interfaces and using interfaces may reduce casting data between components and modules, especially in the boundaries of a single solution.
Also, rules are often applied on interfaces, so DTOs should use them.
I'm new to coding for web, so this may be going the wrong direction, but I've got a DTO from a database, and I want to expose different bits of it for different views. I've encoded this using interfaces on the single DTO (using conditional serialization to ensure only the bits I want are exposed).
I'm also using interfaces on incoming data structures so I can use the same DTO, but mock it in my unit tests.
Related
I'm a novice trying to wrap my head around MVVM. I'm trying to build something and have not found an answer on how to deal with this:
I have several models/entities, some of which have logical connections and I am wondering where/when to bring it all together nicely.
Assume we have a PersonModel:
public class PersonModel
{
public int Id { get; set; }
public string Name { get; set; }
...
}
And a ClubModel:
public class ClubModel
{
public int Id { get; set; }
public string Name { get; set; }
...
}
And we have MembershipModel (a Person can have several Club memberships):
public class MembershipModel
{
public int Id { get; set; }
public PersonId { get; set; }
public ClubId { get; set; }
}
All these models are stored somewhere, and the models are persisted "as in" in that data storage.
Assume we have separate repositories in place for each of these models that supplies the standard CRUD operations.
Now I want to create a view model to manage all Persons, e.g. renaming, adding memberships, etc. -> PersonMangementViewModel.
In order to nicely bind a Person with all its properties and memberships, I would also create a PersonView(?)Model that can be used in the PersonManagementViewModel. It could contain e.g. view relevant properties and also the memberships:
public class PersonViewModel : PersonModel
{
public Color BkgnColor { get return SomeLogic(); }
public IEnumerable<MembershipModel> { get; set; }
...
}
My question here is, how would I smartly go about getting the Membership info into the PersionViewModel? I could of course create an instance of the MemberShipRepo directly in the PersionViewModel but that seems not nice, especially if you have a lot of Persons. I could also create all repositories in the PersonManagementViewModel and then pass references into the PersonViewModel.
Or does it make more sense to create another layer (e.g. "service" layer) that returns primarily the PersonViewModel, therefore uses the individual repositories and is called from the PersonManagementViewModel (thus removing the burden from it and allowing for re-use of the service elsewhere)?
Happy to have pointed out conceptional mistakes or some further reading.
Thanks
You are creating separate model for each table I guess. Does not matter, but your models are fragmented. You can consider putting related data together using Aggregate Root and Repository per Aggregate root instead of per model. This concept is discussed under DDD. But as you said you are new to MVVM, there is already lot much to learn. Involving DDD at this stage will only complicate the things.
If you decide to keep the things as is, best and quick thing I can guess is what you are doing now. Get instance of model from data store in View Model (or whatever your location) and map somehow. Tools like Automapper are good but they does not fit each situation. Do not hesitate to map by hand if needed. You can also use mix approach (Automapper + map by hand) to simplify the things.
About service layer, sure... why not. Totally depends on you. If used, this layer typically contain your business logic, mapping, formatting of data, validations etc. Again, each of that thing is up to you.
My suggestions:
Focus on your business objectives first.
Design patterns are good and helpful. Those are extract of many exceptionally capable developers to solve specific problem. Do use them. But, do not unnecessarily stick to it. Read above suggestion. In short, avoid over-engineering. Design patterns are created to solve specific problem. If you do not have that problem, then do not mess-up your code with unnecessary pattern.
Read about Aggregate Root, DDD, Repository etc.
Try your best to avoid Generic Repository.
I've been entering the advanced stage of C# recently and I've seen a lot of applications that implement losely coupling and dependency injection. I've seen the word "Service" a lot associated with classes, I suppose you would call them Service classes? I've also seen classes in this project which include the word Repository, say you has a called 'Player', there would be 2 more classes 'PlayerService' and 'PlayerRepository' classes.
I've checked Linda, TreeHouse, Udemy and many other sites. I've even google the subject but it seems to bring up hundreds of results all leading to different things. None of these links really answer my question in simple plain detail, atleast none that I can understand.
Can anyone help explain this? Why do I need them, when should I use them, what are they?
Well, hard to make a specific explanation without seeing the code but in general terms the concept of a Repository refers to data layer components and the term service - mostly in ASP.NET world refers to business layer components.
You separate these layers from each other so they can be maintained, tested, expanded in isolation. Ideal architectures expose the functionality of these layers via Interfaces - especially the Repository layer. On the Service layer you can take these dependencies through constructor as Interfaces. Using an IoC container and Dependency Injection patterns, you can then register concrete classes to these interfaces and build your objects in a central location aka. Object Composition Root. that allows you easily manage your dependencies in a central location, rather then each dependency instantiated, passed around in scattered places within your code.
This answer is just a pointer to give you an overview. These are topics you should delve deeper by self research and digest.
The Repository pattern is used to abstract away how a class is persisted. This allows you to change the underlying Database or ORM mapper without influencing the persisted classes. See Using Repository Pattern for Abstracting Data Access from a Cache and Data Store.
A service is used if multiple classes are taking part in a certain usecase and none of these classes should have the responsibility to coordinate the other classes. (Maybe these classes do not even hold direct references to each other.) In this case, put the code that handles the interplay between the classes into a service method and pass the affected objects to it.
Note that if the affected classes are in a direct parent-child relationship, you could let the parent coordinate its children directly, without introducing a service. But this might lead to code that is hard to understand.
Let me give an example: assume we want to commit Transactions. After a Transaction was commited, we want to update the Person who has the transaction with the (denormalized) timestamp of the most recent transaction. As you can see, Person does not hold a direct reference to the transaction.
public class Person {
public long Id { get; set; }
public string Name { get; set; }
public DateTime? LastTransactionTimestamp { get; set; }
}
public class Transaction {
public long Id { get; set; }
public long PersonId { get; set; }
public DateTime Timestamp { get; set; }
public void Commit() {
Timestamp = DateTime.Now;
}
}
Now we have the problem where we should put the logic. If we put it into the Person class, it would need Repository access to load the Transaction (because it holds no direct reference). But it should only be concerned with storing its own data, not loading unrelated data from the DB. If we put it into the Transaction class, it does not know if it was the latest Transaction for this Person (because it does not see the other transactions).
So the solution is to put the logic into a service. If the service needs DB access, we inject a repository into it.
public class PersonTransactionService {
private readonly IDbSet<Transaction> _allTransactions;
public PersonTransactionService(IDbSet<Transaction> allTransactions) {
_allTransactions = allTransactions;
}
public void Commit(Person person, Transaction transaction) {
transaction.Commit();
var mostRecent = _allTransactions
.Where(t => t.PersonId == person.Id)
.OrderBy(t => t.Timestamp)
.LastOrDefault();
if (mostRecent != null) {
person.LastTransactionTimestamp = mostRecent.Timestamp;
}
}
}
I have ASP.NET MVC website and a Class Library for Entity FrameWork
Now i need to had some data valitation using IValidatableObject.
So i have in Class Library entity framework this:
public class ClientA
{
public Guid ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
And in MVC project I have:
public class Client: ClientA, IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext){..}
}
But i got error make cast here:
Client client = new Client();
client.FirstName = "aaaa";
ClientA cl = (ClientA)client;
context.Clients.Add(cl); //error here: Type are different
Any ideas?
Mapping the objects might be preferable to casting, for example
ClientA c1 = new ClientA
{
ID = client.ID,
FirstName = client.FirstName,
LastName = client.LastName
}
This of course could get very tedious, especially if you have big objects, but you could use a tool like Automapper, which can be a time saver when mapping objects with same named properties.
Also, as other answers have suggested, there is no need for your view model (that's what Client essentially is) to inherit from ClientA, even if they have the same properties. Validation is not a concern of class 'ClientA' and this would be more obvious with a more complex class, for example if you ever need to hide properties from the UI or address concerns like globalization/localization.
Use composition instead of inheritance. Most programmers after learning OOP think only in Inheritance/Polymorphism/Encapsulation.
You can instead put a thing inside another thing that validates it.
public abstract class Validator<T>
: IValidatableObject
{
public T Value { get; }
public abstract IEnumerable<ValidationResult>
Validate(ValidationContext validationContext);
}
First answer I am going to give you.
Your instinct is wrong. The validation logic SHOULD live in your data objects in the Business Layer (not the persistence layer, perhaps your issue is that you didn't separate out BL and persistence).
This is why IValidatableObject lives in System.ComponentModel.DataAnnotations and not in System.Web.
This way when your application is a hit and you need to port it to windows phone (pfffhahahahaha), you don't need to rewrite your validation code.
It would also allow you to override SaveChanges() on your DbContext to1 run your validation just before you save.
1 You actually don't need to do that because EF already WILL do that for you...
What you are trying to do is wrong for many reasons:
Problems
1. Type safety
context.Clients.Add(cl);
You are trying to add a ClientA variable to a Client collection. This is not possible since Client is a superType of ClientA. The C# compiler cannot upcast ClientA variable to its super type Client even when cl actually holds a Client object. Why are you casting to ClientA anyway? It should compile if you add client variable instead
2. Entity Framework
...Client: ClientA ...
This line by default will make EF treat the hierarchy as two different entities using TPH (Table per Hierarchy). This is definitely not what you are trying to achieve since you are only using Client as validation
3. Encapsulation
... Client: ClientA, IValidatableObject
As #Aron has stated validation logic is the resposability of the Client (or ClientA) class.
Therefore there should be only one class
public class Client : IValidatableObject
This class is responsible for holding its properties, validation and logic. IValidatableObject interface its considered a core library so feel free to implement it on your Entity
Enough with the problems now the solutions...
Solutions
1. Only one Client class
public class Client : IValidatableObject
This solution is simple, well encapsulated, works great with EntityFramework and keeps logic where it should be.
This is how you must think when constructing a Domain layer
But unfortunately this layer doesn't live by itself. It should be consumed by your presentation layer and probably you were splitting this class in two because your Validate method contains presentation logic
So this give us the next solution...
2. ViewModels
//In your domain layer
public class Client
{
....
}
//In your presentation layer
public class ClientViewModel : IValidatableObject
{
//...
// Same properties as Client
//...
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext){ ... }
}
Notice how ClientViewModel does not inherit from Client. It keeps the same properties as the entity but they aren't related in an inheritance hierarchy. So you have two ways of instantiating a ClientViewModel out of a Client entity.
Manually using a Constructor, BuilderMethod, or anything else that involves calling a new ClientViewModel() somewhere and manually coping the properties, one by one or with reflection (Please don't do reflection)
With a OOM (Object-Object Mapper): Being Automapper one of the most popular libraries. With this option you can register a map with Mapper.CreateMap<Client, ClientViewModel>(); and get a new ClientViewModel from a Client with var clientViewModel = Mapper.Map<ClientViewModel>(client);
Q. But wait, what about the logic in the Entity.
A. You can still make the entity an IValidatableObject too. that way it will handle pure domain validation, leaving the viewmodel with the UI validation.
Stay tuned for more solutions comming soon...
You can use AOP instead of inheritance.
Look at projects like PostSharp to add your validation logic to your data class after you compile.
Let's say that I want to create a blog application with these two simple persistence classes used with EF Code First or NHibernate and returned from repository layer:
public class PostPersistence
{
public int Id { get; set; }
public string Text { get; set; }
public IList<LikePersistence> Likes { get; set; }
}
public class LikePersistence
{
public int Id { get; set; }
//... some other properties
}
I can't figure out a clean way to map my persistence models to domain models. I'd like my Post domain model interface to look something like this:
public interface IPost
{
int Id { get; }
string Text { get; set; }
public IEnumerable<ILike> Likes { get; }
void Like();
}
Now how would an implementation underneath look like? Maybe something like this:
public class Post : IPost
{
private readonly PostPersistence _postPersistence;
private readonly INotificationService _notificationService;
public int Id
{
get { return _postPersistence.Id }
}
public string Text
{
get { return _postPersistence.Text; }
set { _postPersistence.Text = value; }
}
public IEnumerable<ILike> Likes
{
//this seems really out of place
return _postPersistence.Likes.Select(likePersistence => new Like(likePersistence ));
}
public Post(PostPersistence postPersistence, INotificationService notificationService)
{
_postPersistence = postPersistence;
_notificationService = notificationService;
}
public void Like()
{
_postPersistence.Likes.Add(new LikePersistence());
_notificationService.NotifyPostLiked(Id);
}
}
I've spent some time reading about DDD but most examples were theoretical or used same ORM classes in domain layer. My solution seems to be really ugly, because in fact domain models are just wrappers around ORM classes and it doens't seem to be a domain-centric approach. Also the way IEnumerable<ILike> Likes is implemented bothers me because it won't benefit from LINQ to SQL. What are other (concrete!) options to create domain objects with a more transparent persistence implementation?
One of the goals of persistence in DDD is persistence ignorance which is what you seem to be striving for to some extent. One of the issues that I see with your code samples is that you have your entities implementing interfaces and referencing repositories and services. In DDD, entities should not implement interfaces which are just abstractions of itself and have instance dependencies on repositories or services. If a specific behavior on an entity requires a service, pass that service directly into the corresponding method. Otherwise, all interactions with services and repositories should be done outside of the entity; typically in an application service. The application service orchestrates between repositories and services in order to invoke behaviors on domain entities. As a result, entities don't need to references services or repositories directly - all they have is some state and behavior which modifies that state and maintains its integrity. The job of the ORM then is to map this state to table(s) in a relational database. ORMs such as NHibernate allow you to attain a relatively large degree of persistence ignorance.
UPDATES
Still I don't want to expose method with an INotificationService as a
parameter, because this service should be internal, layer above don't
need to know about it.
In your current implementation of the Post class the INotificationService has the same or greater visibility as the class. If the INotificationService is implemented in an infrastructure layer, it already has to have sufficient visibility. Take a look at hexagonal architecture for an overview of layering in modern architectures.
As a side note, functionality associated with notifications can often be placed into handlers for domain events. This is a powerful technique for attaining a great degree of decoupling.
And with separate DTO and domain classes how would you solve
persistence synchronization problem when domain object doesn't know
about its underlying DTO? How to track changes?
A DTO and corresponding domain classes exist for very different reasons. The purpose of the DTO is to carry data across system boundaries. DTOs are not in a one-one correspondence with domain objects - they can represent part of the domain object or a change to the domain object. One way to track changes would be to have a DTO be explicit about the changes it contains. For example, suppose you have a UI screen that allows editing of a Post. That screen can capture all the changes made and send those changes in a command (DTO) to a service. The service would load up the appropriate Post entity and apply the changes specified by the command.
I think you need to do a bit more research, see all the options and decide if it is really worth the hassle to go for a full DDD implementation, i ve been there myself the last few days so i ll tell you my experience.
EF Code first is quite promising but there are quite a few issues with it, i have an entry here for this
Entity Framework and Domain Driven Design. With EF your domain models can be persisted by EF without you having to create a separate "persistence" class. You can use POCO (plain old objects) and get a simple application up and running but as i said to me it s not fully mature yet.
If you use LINQ to SQL then the most common approach would be to manually map a "data transfer object" to a business object. Doing it manually can be tough for a big application so check for a tool like Automapper. Alternatively you can simply wrap the DTO in a business object like
public class Post
{
PostPersistence Post { get; set;}
public IList<LikePersistence> Likes { get; set; }
.....
}
NHibernate: Not sure, havent used it for a long time.
My feeling for this (and this is just an opinion, i may be wrong) is that you ll always have to make compromises and you ll not find a perfect solution out there. If you give EF a couple more years it may get there. I think an approach that maps DTOs to DDD objects is probably the most flexible so looking for an automapping tool may be worth your time. If you want to keep it simple, my favourite would be some simple wrappers around DTOs when required.
The following type of design I have seen basically has "thin" classes, excluding any type of behaviour. A secondary class is used to insert/update/delete/get.
Is this wrong? Is it anti OOP?
User.cs
public class User
{
public string Username { get; set; }
public string Password { get; set; }
}
Users.cs
public class Users
{
public static User LoadUser(int userID)
{
DBProvider db = new DBProvider();
return dp.LoadUser(userID);
}
}
While your user.cs class is lending itself towards a domain transfer object, the Users.cs class is essentially where you can apply business rules within the data-access objects.
You may want to think about the naming convention of your classes along with the namespaces. When I look at a users.cs, I'm assuming that it will essentially be a class for working with a list of users.
Another option would be to look into the Active Record Pattern, which would combine the two classes that you've created.
User.cs
public class User
{
public string Username { get; set; }
public string Password { get; set; }
public User(int userID)
{
//data connection
//get records
this.Username = datarecord["username"];
this.Password = datarecord["password"];
}
}
I would classify it as a domain object or business object. One benefit of this kind of design is that it keeps the model agnostic of any business logic and they can be reused in different kind of environments.
The second class could be classified as a DAO (Data Access Object).
This pattern is not anti-oop at all and is widely used.
I think you're implementing a domain model and a data-access object. It's a good idea.
The first class is anti-OOP because it contains data without behaviour, a typical example of an anemic domain model. It's typical for people who do procedural programming in an OO language.
However, opinions are devided on whether it makes sense ot put DB access logic into the domain model itself (active record pattern) or, as in your code, into a separate class (Data Access Object pattern), since DB access is a separate technical concern that should not necessarily be closely coupled with the domain model.
It looks like it could be the repository pattern this seems to be an increasingly common pattern and is used to great affect in Rob Conery's Storefront example Asp.Net MVC app.
You're basically abstracting your data access code away from the Model, which is a good thing, generally. Though I would hope for a little guts to the model class. Also from previous experience, calling it Users is confusing, UserRepository might be beter. Also might want to consider removing static (which is a hot debate) but makes mocking easier. Plus the repository should be implementing an interface so you can mock it and hence replace it with a fake later.
It's not really object-oriented in any sense, since the object is nothing but a clump of data sticking together. Not that that's a terrible thing.