Thursday, September 26, 2019

Summary of All Data Source Patterns

Simple Active Record (No Repository ) == RDG++
Simple Data Mapper (No Repository) ==  TDG++

Respository Based Active Record = Simple Active Record++
Repository Based Data Mapper = Simple Data Mapper++

Respository (Active Record) = Simple Active Record++
Repository (Data Mapper) = Simple Data Mapper++


When we are using ADO.NET and writing our own DAL, we are not using any ORM.
We are dealing ourself with all dirty work of Data Access

Writing SQL,Connections, Resultset fetching n mapping, exceptions, messaging,
casting, transactions,updating the database schema and domain model ourself

ORMs try to abstract these things out and make our life easy

Linq like language for quering data.
No connection management
No Result set dealing and mapping to Domain Model
No exception handling
No messages to upper layers
No Data type casting
No Transation Mgmt, it is done by UOW and Change Tracker
Database schema and Domain is synched by Code First Migrations

Two Types of Data source Patterns

1. Row Based Patterns
a. Row Data Gateway (No Domain Logic, Only Persistence Logic, Seperate Class for Querying, No Useful Pattern even for CRUD and BREAD)
b. Active Record (Domain Logic, Persisteance Logic, No SOC, Data, Getter, Setters in same Class, Improvment over RDG, used most in CRUD or BREAD scenarios, it is improvment of a)

2. Table Based Patterns
a. Table Data Gateway (No Domain Logic, Only Persistence Logic, Good SOC, Takes Primitive Data Types, Return Connected ResultSets, Not Useful Pattern even for CRUD and BREAD)
b. Data Mapper Pattern (Domain Logic, persistence Logic, Good SOC, Takes Entities/Domianobj/DTO as input, Returns disconnected Entities/DomainObj/DTO, Improvment over TDG, used most in CRUD and Bread, it is an improvment over a)

Above discussion clearly say

Active Record == Improvment over the RDG
Data Mapper == Improvement over the TDG

Active Record == RDG++
Data Mapper ==  TDG++

Active Record is good for extermely simple CRUD Domains
Data Mapper is good for exetremely complex Domain Centric scenarios

Most ORM provide support for above 2 patterns, both B are best
Rest of the Two Patters are dumb both As are dumb

In ORMs I think we have two types of Implement of ARP and DM Patterns

Intially we have Non-Repository Based half cooked implemenation of B Patterns, these implemetations remove 50% fo the dirty Data Access Job
We still have to do the dirt work of SQL Queries, Transaction Management, Custom UOW Classes, Custom Repositories
Non Repostory based Active Record Pattern
Non Repository based Data Mapper Pattern

Lately we have Repository Based fully cooked implementations of B Patterns, these implementations remove 90% of the dirty Data Access Job,
It prominently the provide, In-memory Repositories, LINQ Querying, UOW, Change Tracker.
Repostory based Active Record Pattern
Repository based Data Mapper Pattern

Simple Active Record (No Repository ) == RDG++
Simple Data Mapper (No Repository) ==  TDG++

Respository Based Active Record = Simple Active Record++
Repository Based Data Mapper = Simple Data Mapper++

Respository (Active Record) = Simple Active Record++
Repository (Data Mapper) = Simple Data Mapper++

Saturday, February 9, 2019

Three Roles of DBContext and DBSet in ASP.NET MVC

Three Roles of DBContext and DBSet in ASP.NET MVC

DBContext and DB Set in asp.net mvc has 3 roles

1. They act as the Virtual DB in the application. It is the representation of DB in the application, Connection Strings is related to it. All tables and repositories are in this class. This class is the base to the DB Connectivity in the application. Whereever we need DB functionality we need this class.

2. This class is the base to the Code First Migrations. This class hold the Entity Configurations. This class hold the Domain Model elements those we need to represent in the DB. This class glue the Domain Model and the DB Schema. Code First Migrations are done in the Context of DB Set represented in this class. All Entity Configurations/Fluent APIs are related to this class. Seed method is related to the Configuration class in Migration folder.

3. This class is central to the UOW/Repository in the ASP.NET MVC, DBContext is EF UOW, and DB Set is EF Repository using both in the Controller or Services does not yeild the benifits of UOW/Repo. We need to have Application Sepecific UOW and Entity specific Repo, to have the full benifits of UOW/Repo. Application specific UOW and Entity specific Repo are defined on the top of EF-UOW and Repo.

Application Specific UOW Class & Interfaces Samples



namespace CleanArchitecture.Application.Interfaces
{
    public interface IDatabaseService
    {
        IDbSet<Customer> Customers { get; set; }

        IDbSet<Employee> Employees { get; set; }
       
        IDbSet<Product> Products { get; set; }
       
        IDbSet<Sale> Sales { get; set; }

        void Save();
    }
}

Friday, February 8, 2019

How to implement UOW and Repository in OCH Architecture

EF provide UOW (DbConext) and Repositories (DbSet) but using them directly in
Controllers or Services is not required. Doing so reuslts in all disadvanges of poorly
architectured code.
We need to have Wrappers around EF UOW (DbConext) and Repositories (DbSet)
We put interfaces on top of these wrappers IUnitOfWork and IRepositories
Services and Controllers use these Interfaces to do persistence
All these interfaces are defined inside the Service or Controller layer
DI/IOC is used to intect depedencies to controllers or Services
Only then we get benifits of Good Arch

Why Service layer in Clean Architecture is a burden

Why Service layer in Clean or Onion or Hexagonal Architecture is a burden

Mosh is no OK with OCH architecture in defintion.
Overhead of Service Layer, if there is not complex application loigc and feature slice is very thin
Little bit application logic or orchestration of calling Domain Logic will go to Repositories or Controllers
Controller will know about the Domain Classes I think.
Mosh Arch == OCH Arch - Service Layer
No Physical Layers Projects, it increases complexity of Code base
Just Logical Layers in Projects, it increases understability.
Layers violatins are detected by Code Reviews
In case of Multiple Clients, we expose the Web API Controllers to expose the functionality,
No need of App. Services for exposing App Functionalitiy to Multiple Clients
Two Layers of Indrections make the Vertical Feature Slice complex, to understand, develop and maintain
Two Phases of Data Mappings make the Vertical Feature Slice complex, to understand, develop and maintain
We should use the Minified-Mosh-Version of OCH architecture.
Only add the services if the feature is fat and need orchestration
If the feature is flat CRUD Operation, do not go for that.
If the feature is fat, we need big Request Processing Pipeline, add componets in the pipeline
If the feature is flat CRUD, then Controller talking to Enitty Repository and Domain objects having little logic inside them is ok, little application logic will live inside the Controller or Repository. It is OK
Extension Methods on DbSet is the replacement of EntityRepsitories
TDD is the solution of spghetti often broken code. We still have to change things at many places, hampers productivity, understandability, hampers teamwork, More Merge Conflicts, Complex deployment, recompilation, re deployment,


1. Services Classes Command and Query Classes
2. Interfaces for Service Classes
3. Request Repose Models for Data Containers (No Interfaces required)
4. Seperate Testing Classes for Services
5. DI Classes, One extra layer of Indirection, to inject Repositories to Services
6. Mapping Code, Extra mapping code that map Domain obj to Request Response Model
7. Managing References for different projects, external referecnes, internel references

Where and When to Apply DDD

Problems is DDD community has come with elegant solutions for extremely complex business domains
When they come and share those solutions, they do not shared the context or very naively share the context
They describe this as extension of traditional 3 level arch and everybody start following them blindly with knwoing about the context
One should study his app context, one should study the solution business context and take that solution if the context is same
By the large 90% EAs are CRUD having little or not business or application logic
Remaining 10% complex business EA are 80% CRUD.
We take the Areoplance Structure and start fitting Auto Bike components inside it. Both are correct in isolation but their combination is wrong.
Auto Bike built with Aeroplance Structure result in extremely complex Auto Bike

Dependency Inversion Principle by Mosh Hamedani

Ist part of DIP
High Level Module ==> Interface/Contract/Abstraction ==> Low Level Module/Details
HLM should not depend upon LLM, both should depend upon abstraction
There should exist an interface between HLM/Layers and LLM/Layers
These Interfaces are defined inside the HLM layer.
If the Contract remain the same, High level module will be not effected.
If the Contract is simple and clean and thoughtful, predictive, chances are it will not change

2nd part of DIP
High Level Module ==> Interface/Contract/Abstraction <== Low Level Module/Details
Abstractions should not depend upon details, Details should depend upon Abstractions
Interface should be pure and generic, they should not have to leaky
Interface should be defined interms of only Interfaces.
Interface Methods should not use the Types with in LLM
All these interfaces are defined inside the HLM
If layers. LLM layer include the reference of HLM layer.
Arrows show the Dependency Flow not the Control Flow a runtime.