Tuesday, December 18, 2018

Blog I am Interested


http://www.taimila.com/blog/.net-solution-structure-of-an-enterprise-application/

https://hendryluk.wordpress.com/2009/08/17/software-development-fundamentals-part-2-layered-architecture/

https://www.oreilly.com/library/view/software-architecture-patterns/9781491971437/app01.html
https://www.oreilly.com/library/view/software-architecture-patterns/9781491971437/

https://www.bennadel.com/blog/recent-blog-entries.htm

Martin Fowler

Robert C Martin

Mosh Hamedani
programmingwithmosh
codewithmosh

Steve Smith Oradalish

https://ardalis.com/
http://www.weeklydevtips.com/025

Dev IQ
https://deviq.com/repository-pattern/

Jimmy Bogard
https://lostechies.com/jimmybogard/
https://jimmybogard.com/


Julie Larmen Data Farm

Matthew Renezee

Jeferry Plemero

Alastair Cookburn

Udi Dahan
http://udidahan.com/2011/04/22/when-to-avoid-cqrs/

Scott Hanselmens

Scott Guthrie

Scott Allen

Zankav Taskin
http://www.zankavtaskin.com/p/about-me.html
https://github.com/zkavtaskin/Domain-Driven-Design-Example

Eric Evans
https://domainlanguage.com/
http://dddcommunity.org/

Vaughn Vernon
https://vaughnvernon.co/

Jimmy Nelson

Scott Millet

Gregor Hophe

Greg Young

Roy Oshere TDD

Dan North

Jim Coplien

Micro Services
https://microservices.io/

Scott Ammber
http://www.ambysoft.com/books/agileDatabaseTechniques.html
http://agiledata.org/
http://enterpriseunifiedprocess.com/
http://www.ambysoft.com/unifiedprocess/agileUP.html
http://agilemodeling.com/
http://www.agiledata.org/essays/mappingObjects.html

========================

http://cqrs.nu/Faq/commands-and-events

Monday, December 17, 2018

Generic Repository and Mosh

“Instead, you should have a separate repository per domain class, like OrderRepository, ShippingRepository and ProductRepository.”
Hi Mosh,
Do you mind to
share your thought about Generic Repository pattern? What do you think about it?
Thanks.

Generic repository is good as long as your methods don’t method IQueryable. Otherwise, it’s like you’re wrapping DbSet with another class with the same interface. No point in doing that!
It’s useful when you wanna get simple objects (like reference data) without having to create a separate repository for each entity.

Application Services Should Not Be Used in Read Operations Mosh Blog

Hi Mosh,
I agree with you that the repository must return only domain entities. If you want to return ViewModel objects, it’s possible to create a Service layer that would be responsible for get domain entities using a repository and convert to ViewModels. Finally, the controller(mvc or webApi) could use these services and know nothing about the entities.
Leave your comments.
Have a nice day!
Hi Clayton,
Services should not return ViewModels 
A ViewModel is part of the presentation layer which sits above the service layer. 
Mapping of domain objects to ViewModels is the responsibility of whoever wants to display those objects. 
In an ASP.NET MVC application, it’s the controller, in a WPF application it’s the Form (or Window).
Services are often misunderstood. Technically, your services should be used only for the write operations and not for reading data. 
It took me a little while to really grasp this. The reason is that if a controller needs some data from the database, it can simply use the repository interfaces to get the data. There is no need to go through a service layer for getting data. 
With Application Services in Read Operations, you’ll end up with services methods that have 1 line of code, which is simply delegating to the repository. What’s the point of these methods? Nothing but increasing the development and maintenance cost. I had a lot of services like these several years ago but eventually, I came to this realization that these methods are redundant and add absolutely no value.
Just to clarify, controller uses the repository interface (not the implementation). So it doesn’t go straight to the data access layer. Repository interfaces are part of the business layer or the core domain.
Hope that helps!


======================================================
My Take on above
Above Question is asking for decoupling the Presentation Layer or Controller from the 
Domain Layer. 
Typically Hexagonal Architecture asks for decoupling the UI/Presentation/Controller from the Domain Layer and it is done as follows in case of Fetch Operations
UI <== Controller <== AS <== Repository<==EF<==DB
ViewModel<==Model<==DomainObject
But Mosh is saying it wastage of time and code if we involve AS in the Fetch Operations
UI <== Controller <== Repository<==EF<==DB
ViewModel<==DomainObject

Sunday, December 16, 2018

Layered Architecture in ASP.NET Core Applications

 
Comments

Layered Architecture in ASP.NET Core Applications

One of the viewers of my YouTube channel asked me an interesting question. He mentioned in a typical layered architecture, he sees ASP.NET MVC building blocks (Controller, View, and Model) as part of the presentation layer. These days, however, a lot of modern applications are built with Angular/React on the client and ASP.NET Core (Web API) on the server. So, what is the presentation layer in this kind of architecture? Let’s see!
With this stack, we have the following layers:
  • Presentation
  • Service
  • Business Logic/Application Core
  • Data Access/Persistence

Presentation Layer

Your Angular components, their templates, and the models you define in your Angular app are all presentation layer artifacts.

Service Layer

The confusing thing about this layer is that the term “service” is overloaded and it means different things to different people. In the context of a layered architecture, it wraps an application and exposes the application functionality in terms of a simple API that the user interface can talk to. This is the classic definition. Think of it as the glue between the presentation and business logic layers.
Now, in our modern stack, our logical service layer is physically composed of two parts: one part is on the client (Angular HTTP services) and the other part is on the server (ASP.NET Core controllers). These Angular services and ASP.NET Core controllers are very cohesive. The methods on these services (eg CourseService.getCourses()) talk directly to the endpoints exposed by your ASP.NET Core controllers.

Business Logic Layer

In your ASP.NET Core controllers, you often use repository interfaces (ICourseRepository), domain classes (Course) and services (PhotoService). All these are part of the business logic layer. They represent the core of an application irrespective of any presentation or persistence frameworks.
Note that here I’m talking about repository interfaces and not their implementations. These implementations are part of the data access/persistence layer.
Also, note that the services we have here are responsible for orchestration. For example, when adding a photo to a course, first, you need to store that photo in the file system (or some other kind of storage), and then you need to add it to the database (using a repository interface). Here is an example:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
// Store the file first
var uploadsPath = Path.Combine(host.WebRoot, "uploads");
if (!Directory.Exists(uploadsPath))
    Directory.CreateDirectory(uploadsPath);
 
var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
var filePath = Path.Combine(uploadsPath, fileName);
 
using (var stream = new FileStream(filePath, FileMode.Create))
    file.Copyto(stream);
}
 
// Add a record to the database
var photo = new Photo { FileName = fileName };
repository.Add(photo);
unitOfWork.Complete();
You wouldn’t write all this logic inside an ASP.NET Core Controller. Imagine, tomorrow you decide to use a different framework. You want to re-use as much code as possible. By encapsulating this code in a service (PhotoService.AddPhoto()), you can switch from ASP.NET Core to a different framework with less effort.

But wait for a second…

Now, that strongly-opinionated developer comes and says: “But who does replace ASP.NET Core with something else? How often does that happen?” Let’s say never! By moving all this logic from a controller into a service, you put the responsibility where it really belongs. The result is cleaner, slimmer, easier to read and easier to test controllers.
Imagine a restaurant where the chef does it all. He’s at the door, welcoming guests, giving them a table, taking their order, then going in the kitchen, chopping the vegetables, cooking, washing the dishes, then coming out and giving the bill to the guests. Would you go to that restaurant? I hope not!
In a good and organized restaurant, there are a few people each focusing on only one job. The waiters/waitresses are purely responsible for welcoming the guests and giving them the bill. The chef is purely responsible for cooking. He or she doesn’t wash the dishes! By the same token, you should have classes that do only one thing and do it well. This is what we call separation of concerns. You should put the responsibility where it really belongs, even if you’re never going to change the presentation or persistence framework of your application.
So, once again, all your domain classes (Course), repository interfaces (ICourseRepository) and application services (PhotoService) are part of the business logic layer. They represent the core of your application completely decoupled from any presentation and persistence frameworks. This is what Uncle Bob defines as Clean Architecture.

Data Access Layer

This layer is all about persistence. Here we have implementations tightly coupled to Entity Framework (or other frameworks) for persisting and retrieving data. If you’re using Entity Framework, your DbContext belongs in this layer. So do UnitofWork and Repositoryimplementations.

Splitting a Project

Now, a common (and bad) practice I’ve seen some developers do, is that they blindly split an ASP.NET project into multiple class libraries, one for each layer. And with this, they assume just because they have a class library called MyProject.BLL or MyProject.DAL, they have properly layered their application. But that’s not necessarily right.
What matters is the direction of dependency and coupling between classes, not folders or projects. You can easily organize your classes into folders and projects but these classes can be poorly coupled to each other, which results in spaghetti architecture. Read my blog post on the topic:

If you learned something from this post, please share it and drop your comments/questions below.

Comments Repositories or Command / Query Objects?

 
Comments

Repositories or Command / Query Objects?

This is a follow up post to my YouTube video Repository Pattern, Done Right. If you haven’t seen this video, it’s best to watch it first, before continuing reading.
There have been many interesting questions in the discussion area and I’ve replied to most (if not all) of them. One that has come up a few times is:
Should we favour command/query objects over repositories?
A few have referred me to Jimmy Bogard’s post. So, in this post, I’ll be comparing these two approaches and pros / cons of each.
Before I get started, I need to emphasise: neither the repository pattern, nor command / query objects, are silver-bullets. Just because these architectural patterns exist, doesn’t mean you should use them in every single application. If your queries are simple enough (one or two lines), don’t worry about creating an abstraction over them. There is nothing wrong with writing them in your controllers (assuming a web application).
If you do, however, have fat queries that have bloated your controllers, you might want to consider one of these patterns to achieve “better separation of concerns”.

Repository vs Command / Query object

In a repository, we often have many methods, all related to a specific entity:
1
2
3
4
GetUpcomingGigs()
GetGigsIAmAttending()
GetMyGigs()
GetPopularGigs()
When you promote one of these methods to a class, you’ll end up with what we call a query object.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
public class GetPopularGigsQuery
{
     private GigsContext _context;
 
     public GetPopularGigsQuery(GigsContext context)
     {
          _context = context;
     }
 
     public IEnumerable<Gig> Execute()
     {
          return _context.Gigs
                      .Where(...)
                      .Include(...)
                      .Include(...)
                      .Include(...)
                      .OrderByDescending(...)
                      .Take(10)
                      .ToList();
     }
}
So, what you see in the Execute() method here, used to be one of the methods of a class like GigsRepository. Now, we’ve promoted that to a class. Have we gained anything here? Absolutely not!
With this approach, if you have a repository with 5 methods, you’ll end up with 5 new classes in your application. Now, take into account how many repository classes you have and eventually how many command / query classes you’ll end up with. You’ll end up with an explosion of classes that don’t provide any additional value than a simple method.

When Command / Query objects provide value

When you want to execute some operation before and / or after the execution of the command / query. Sometimes, in large enterprise applications, you may want to check that the current user has permission to execute a given query (or command), and additionally you may want to log that somewhere.
Without using command / query classes, your repository methods would end up with a lot of duplicate logic:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
public IEnumerable<Gig> GetPopularGigs()
{
     // authorisation logic
 
     // logging logic
      
     return _context.Gigs.......
}
 
public IEnumerable<Gig> GetUpcomingGigs()
{
     // authorisation logic
 
     // logging logic
      
     return _context.Gigs.......
}
At this point, by promoting a method to a class, you’ll have at least a couple of options in front of you to implement the same behaviour in a more elegant way. You can use the template or strategy pattern.
With the template pattern, you would define a base class for your commands or queries like this:
01
02
03
04
05
06
07
08
09
10
11
12
13
public abstract class Query
{
      public void Execute()
      {
           // authorisation logic
 
           // logging logic
  
           DoExecute();
      }
 
      abstract void DoExecute();
}
So, you write the authorization and logging logic only once, in the base Query or Command class. Then, when implementing an actual command or query, you override the DoExecute method:
1
2
3
4
5
6
7
public abstract class GetPopularGigsQuery : Query
{
      public override DoExecute()
      {
           return _context.Gigs....
      }
}
With the strategy pattern, instead of using inheritance, you’d use composition to achieve the same thing. If you need more understanding of inheritance vs composition, check out my C# course: Classes, Interfaces and Object-oriented programming.

What about ASP.NET MVC action filters?

Mosh, aren’t action filters exactly for that? To execute some custom logic (e.g. like authorisation or logging) before each action? True! Then, why bother using the command / query pattern?
Good question! First, you don’t have to use the pattern, if you prefer to use ASP.NET MVC action filters. But what if, in the future, you decide to use a different web presentation framework that doesn’t have the concept of MVC filters? Tools and frameworks come and go. What is popular now, is not going to be popular in a few years time. There was a time we thought ASP.NET WebForms was so cool. Now, it’s almost a dead technology!
If you want to protect your application architecture from change of external tools and framework, you need to decouple it from them by creating your own abstractions. Command / query pattern is one of the ways to create such abstraction. If you switch over to a different presentation framework, you can take all your existing code and re-use it without modifying a single line, and more importantly, without breaking things along the way!

What if…

What if you’re not too concerned about decoupling your application architecture from external tools / libraries? What if you think this is overkill? That’s a perfectly valid argument. Then, don’t use these patterns. As I always say to my students: “Keep it simple”. Use MVC filters to achieve the same result, and if they won’t help you in the future, then you’d spend time solving that new problem, not now.
What if you don’t have such requirements like authorisation and logging before each query? Then, command / query objects don’t give you any additional value. You’ll just waste your time and energy writing more and more code.
What if you don’t have complex queries in the first place? Don’t bother with the repository pattern either!
Every pattern is designed to solve a specific problem. Don’t solve a problem that does not exist!
Till my next post, all the best my friends!