Showing posts with label architecture. Show all posts
Showing posts with label architecture. Show all posts

DDD Building Blocks Dictionary

0

Category : ,

Ubiquitous language

- A common language to help communication between software developers and domain experts.

Invariant

- describes something that must be true with your design all the time.

Bounded Context

- A specific responsibility enforced by explicit boundaries. These boundaries are set by the different way we represent models. Different contexts may have completely different models of common concepts with mechanisms to map between them.
- A Bounded Context can be considered as a miniature application, containing it’s own Domain, own code and persistence mechanisms.
- Communication to and from a Bounded Context is done via a Context Map.

describe things in the domain model

Entity

- A unique thing that has a life cycle and can change state. For example, a conference in a conference management system will be an entity; many of its attributes could change over time (such as its status, size, and even name), but within the system each particular conference will have its own unique identity.

Value object

- Not all objects are defined by their identity. For some objects what is important are the values of their attributes.
- Sometimes in one context something is an entity while in another it is just a value object.

Services

- You cannot always model everything as an object.
- it may make sense to model a third-party payment processing system as a service. The system can pass the parameters required by the payment processing service and then receive a result back from the service.
- A service in a DDD domain model is not a web service. It communicates aggregate roots, performs complex use cases, cross aggregates transaction. An operation offered as an interface that stands alone in the model, with no encapsulated state.

Aggregate

- Whereas entities, value objects, and services are terms for the elements that DDD uses to describe things in the domain model, the terms aggregate and aggregate root relate specifically to the lifecycle and grouping of those elements.
- Aggregate is a cluster of domain objects that can be treated as a single unit to provide a specific functionality and for the purpose of data changes.
- Every aggregate has a unique ID; therefore, you can use that ID to record which aggregate in the system was the source of a particular event.
- In summary, aggregates are the mechanism that DDD uses to manage the complex set of relationships that typically exist between the many entities and value objects in a typical domain model.

Aggregate root

- An aggregate root (also known as a root entity) is the gatekeeper object for the aggregate. All access to the objects within the aggregate must occur through the aggregate root; external entities are only permitted to hold a reference to the aggregate root, and all invariants should be checked by the aggregate root.
- An aggregate root is an entity that composes other entities (as well as its own values) by composition. It is the domain’s only entry point for data access. A heart of your domain.
- Another area where there can be confusion is in distinguishing entities from aggregates. Every aggregate has an entity acting as its aggregate root, and for lots and lots of entities the aggregate will consist of just this entity. The point is that "Customer have Orders" does not mean imply aggregation; Customer, Order and Product are all aggregate roots.

Domain Event

- A Domain Event is something that happened in the past, and that is of interest to the business.
- Domain Events is an immutable array of Domain Event objects. Once they have been initialized, there's no way to change them, there are no setters. Because events happen in the past, they cannot be changed or undone. That makes perfect sense: History can't be altered!
- Events happen in the past. For example, "the speaker was booked," "the seat was reserved," "the cash was dispensed."
- Events can be processed multiple times, by multiple consumers.
- Here are sets of events we may come up with from the cafe tab scenario. TabOpened, DrinksOrdered, FoodOrdered, FoodCancelled, DrinksServed, FoodPrepared, FoodServed, TabClosed.

CQRS — Command-Query Responsibility Segregation

- A common sense rather than a pattern. CQRS just separates a model into two separate parts — READ model and WRITE model.
- They also can be referenced as Query model and Command model. Segregation must be clean so commands can’t return any data.
- A command is any method that mutates state and a query is any method that returns a value.
- CQRS is not a top-level architecture. CQRS is something that happens at a much lower level.

Commands

- Commands are imperatives; they are requests for the system to perform a task or action. For example, "book two places for conference X" or "allocate speaker Y to room Z." Commands are usually processed just once, by a single recipient.
- Commands are things that indicate requests to our domain.
- A command may be accepted or rejected.
- An accepted command leads to zero or more events being emitted to incorporate new facts into the system.
- A rejected command leads to some kind of exception.
- Commands are also identified by looking for verbs. For example OpenTab, PlaceOrder, MarkFoodServed, CloseTab etc. However, they are focused around what the user considers as an operation.

Exceptions

- An important part of the modeling process is thinking about the things that can cause a command to be refused. We are expected to model these "sad paths" into exception types, just as commands and events are expressed as DTOs.
- Looking to the cafe domain scenario, we can identify three notable exceptions we need in our model: CannotCancelServedItem, TabHasUnservedItems and MustPayEnough. The names here try to explain why the command failed.

Command Bus

- The idea of a command bus is that you create command objects that represent what you want your application to do. Then, you toss it into the bus and the bus makes sure that the command object gets to where it needs to go.
- So, the command goes in -> the bus hands it off to a handler -> and then the handler actually does the job. The command essentially represents a method call to your service layer.
- The Command Bus pattern relies on 3 types of classes:
Command (encapsulate our input, does simple validation on it)
CommandHandler (dedicated to a single Command, does the actual logic)
CommandBus (interface allowing us to build Middlewares that calls the appropriate CommandHandle for the given Command)

Query

— an interpreter, which is a structure of objects which can form itself into an SQL query. You can create this query by referring to classes and fields rather than tables and columns. In this way, those who write the queries can do so independently of the database schema and changes to the schema can be localized in a single place.

Event Sourcing

- Event sourcing is a way of persisting your application's state by storing the history that determines the current state of your application. For example, a conference management system needs to track the number of completed bookings for a conference so it can check whether there are still seats available when someone tries to make a new booking.
- ensuring every change to the state of an application is captured in an event object, and that these event objects are themselves stored in the sequence they were applied for the same lifetime as the application state itself.

Repository

- mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
- A mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects.
- pretends to be a collection of Aggregate Roots.



https://developer-paradize.blogspot.com/2016/05/ddd-building-blocks-dictionary.html
https://blog.lelonek.me/ddd-building-blocks-for-ruby-developers-cdc6c25a80d2

Micro Services Dependency Hell

0

Category : ,

Interesting series of articles from Postman, how they implemented Micro-Services architecture, issues encountered and solutions.

Part 1

https://medium.com/postman-engineering/conquering-the-microservices-dependency-hell-at-postman-with-postman-part-1-introduction-a1ae019bb934

Part 2

https://medium.com/postman-engineering/conquering-the-microservices-dependency-hell-at-postman-with-postman-part-2-7c825d576947

Decision Tree

Clean Architecture

0

Category :

Alot of modern architectures(a lit of which is on the original post referenced at the bottom) are trying to achieve the same objective, which is the separation of concerns. They all achieve this separation by dividing the software into layers. Each has at least one layer for business rules, and another for interfaces.

Each of these architectures produce systems that are:

  1. Independent of Frameworks. The architecture does not depend on the existence of some library of feature laden software. This allows you to use such frameworks as tools, rather than having to cram your system into their limited constraints.
  2. Testable. The business rules can be tested without the UI, Database, Web Server, or any other external element.
  3. Independent of UI. The UI can change easily, without changing the rest of the system. A Web UI could be replaced with a console UI, for example, without changing the business rules.
  4. Independent of Database. You can swap out Oracle or SQL Server, for Mongo, BigTable, CouchDB, or something else. Your business rules are not bound to the database.
  5. Independent of any external agency. In fact your business rules simply don’t know anything at all about the outside world.

The diagram at the top of this article is an attempt at integrating all these architectures into a single actionable idea.

The Dependency Rule

The concentric circles represent different areas of software. In general, the further in you go, the higher level the software becomes. The outer circles are mechanisms. The inner circles are policies.

The overriding rule that makes this architecture work is The Dependency Rule. This rule says that source code dependencies can only point inwards. Nothing in an inner circle can know anything at all about something in an outer circle. In particular, the name of something declared in an outer circle must not be mentioned by the code in an inner circle. That includes, functions, classes. variables, or any other named software entity.

By the same token, data formats used in an outer circle should not be used by an inner circle, especially if those formats are generate by a framework in an outer circle. We don’t want anything in an outer circle to impact the inner circles.

Entities

Entities encapsulate Enterprise wide business rules. An entity can be an object with methods, or it can be a set of data structures and functions. It doesn’t matter so long as the entities could be used by many different applications in the enterprise.

If you don’t have an enterprise, and are just writing a single application, then these entities are the business objects of the application. They encapsulate the most general and high-level rules. They are the least likely to change when something external changes. For example, you would not expect these objects to be affected by a change to page navigation, or security. No operational change to any particular application should affect the entity layer.

Use Cases

The software in this layer contains application specific business rules. It encapsulates and implements all of the use cases of the system. These use cases orchestrate the flow of data to and from the entities, and direct those entities to use their enterprise wide business rules to achieve the goals of the use case.

We do not expect changes in this layer to affect the entities. We also do not expect this layer to be affected by changes to externalities such as the database, the UI, or any of the common frameworks. This layer is isolated from such concerns.

We do, however, expect that changes to the operation of the application will affect the use-cases and therefore the software in this layer. If the details of a use-case change, then some code in this layer will certainly be affected.

Interface Adapters

The software in this layer is a set of adapters that convert data from the format most convenient for the use cases and entities, to the format most convenient for some external agency such as the Database or the Web. It is this layer, for example, that will wholly contain the MVC architecture of a GUI. The Presenters, Views, and Controllers all belong in here. The models are likely just data structures that are passed from the controllers to the use cases, and then back from the use cases to the presenters and views.

Similarly, data is converted, in this layer, from the form most convenient for entities and use cases, into the form most convenient for whatever persistence framework is being used. i.e. The Database. No code inward of this circle should know anything at all about the database. If the database is a SQL database, then all the SQL should be restricted to this layer, and in particular to the parts of this layer that have to do with the database.

Also in this layer is any other adapter necessary to convert data from some external form, such as an external service, to the internal form used by the use cases and entities.

Frameworks and Drivers.

The outermost layer is generally composed of frameworks and tools such as the Database, the Web Framework, etc. Generally you don’t write much code in this layer other than glue code that communicates to the next circle inwards.

This layer is where all the details go. The Web is a detail. The database is a detail. We keep these things on the outside where they can do little harm.

Only Four Circles?

No, the circles are schematic. You may find that you need more than just these four. There’s no rule that says you must always have just these four. However, The Dependency Rule always applies. Source code dependencies always point inwards. As you move inwards the level of abstraction increases. The outermost circle is low level concrete detail. As you move inwards the software grows more abstract, and encapsulates higher level policies. The inner most circle is the most general.

Crossing boundaries.

At the lower right of the diagram is an example of how we cross the circle boundaries. It shows the Controllers and Presenters communicating with the Use Cases in the next layer. Note the flow of control. It begins in the controller, moves through the use case, and then winds up executing in the presenter. Note also the source code dependencies. Each one of them points inwards towards the use cases.

We usually resolve this apparent contradiction by using the Dependency Inversion Principle. In a language like Java, for example, we would arrange interfaces and inheritance relationships such that the source code dependencies oppose the flow of control at just the right points across the boundary.

For example, consider that the use case needs to call the presenter. However, this call must not be direct because that would violate The Dependency Rule: No name in an outer circle can be mentioned by an inner circle. So we have the use case call an interface (Shown here as Use Case Output Port) in the inner circle, and have the presenter in the outer circle implement it.

The same technique is used to cross all the boundaries in the architectures. We take advantage of dynamic polymorphism to create source code dependencies that oppose the flow of control so that we can conform to The Dependency Rule no matter what direction the flow of control is going in.

What data crosses the boundaries.

Typically the data that crosses the boundaries is simple data structures. You can use basic structs or simple Data Transfer objects if you like. Or the data can simply be arguments in function calls. Or you can pack it into a hashmap, or construct it into an object. The important thing is that isolated, simple, data structures are passed across the boundaries. We don’t want to cheat and pass Entities or Database rows. We don’t want the data structures to have any kind of dependency that violates The Dependency Rule.

For example, many database frameworks return a convenient data format in response to a query. We might call this a RowStructure. We don’t want to pass that row structure inwards across a boundary. That would violate The Dependency Rule because it would force an inner circle to know something about an outer circle.

So when we pass data across a boundary, it is always in the form that is most convenient for the inner circle.

Conclusion

Conforming to these simple rules is not hard, and will save you a lot of headaches going forward. By separating the software into layers, and conforming to The Dependency Rule, you will create a system that is intrinsically testable, with all the benefits that implies. When any of the external parts of the system become obsolete, like the database, or the web framework, you can replace those obsolete elements with a minimum of fuss.



my thanks to this great blog post:
https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html

High Cohesion, Loose Coupling

0

Category : , ,

We are witnessing a high demand for a maintainable software, software that can change easily over time. In order to prolong the value of the software for a long period of time you have to make it respond easier to change. There are a few guidelines that you can follow that can help you out.

Here, I try to shed some light on two of those: cohesion and coupling

High Cohesion

Cohesion in software engineering is the degree to which the elements of a certain module belong together. Thus, it is a measure of how strongly related each piece of functionality expressed by the source code of a software module is.

Functional Cohesion

Functional cohesion is when parts of a module are grouped because they all contribute to a single well-defined task of the module.

One way of looking at cohesion in terms of OO is if the methods in the class are using any of the private attributes. Below is one example of how a high-cohesion class would look like.

1:    class HighCohesion  
2:    {  
3:      private int _elementA;  
4:      private int _elementB;  
5:    
6:      public int MethodA()  
7:      {  
8:        var returnValue = SomeOtherMethod(_elementA);  
9:        return SomeVeryOtherMethod(_elementB);  
10:      }  
11:    
12:      public void PrintValues()  
13:      {  
14:        Console.WriteLine(_elementA);  
15:        Console.WriteLine(_elementB);  
16:      }  
17:    }  


The point is having a the classes as small as possible in terms of elements. The less elements we have the greater the possibility for them to be used in all the methods.

Loose Coupling

Coupling in simple words, is how much one component knows about the inner workings or inner elements of another one, i.e. how much knowledge it has of the other component.

Correct and clear description of what 1:1 coupling is:

iPods are a good example of tight coupling: once the battery dies you might as well buy a new iPod because the battery is soldered fixed and won’t come loose, thus making replacing very expensive. A loosely coupled player would allow effortlessly changing the battery.


Loose coupling is a method of interconnecting the components in a system or network so that those components, depend on each other to the least extent practically possible…

Tight coupling is where components are so tied to one another, that you cannot possibly change the one without changing the other.

The image above shows us a relation between two classes that is called tight coupling. Class1 above directly instantiates objects of Class2, and even goes as far as accessing member variables and so on. This makes it very dependent on Class2. What if we decided we wanted to add extra parameter in Class2’s constructor and make the default one private? Then we would have to change every usage of Class2 everywhere.
1:    class ClassA  
2:    {  
3:      private bool _elementA;  
4:        
5:      public int MethodA()  
6:      {  
7:        if (_elementA)  
8:          return new ClassB()._elementB;  
9:          
10:        return 0;  
11:      }  
12:    
13:      public void PrintValues()  
14:      {  
15:        new ClassB().MethodB();  
16:      }  
17:    }  
18:    
19:    class ClassB  
20:    {  
21:      public int _elementB;  
22:    
23:      public void MethodB()  
24:      {  
25:        Console.WriteLine(_elementB);  
26:      }  
27:    }  

We can solve this is by so called inverting the dependencies, by adding another layer. Example in C# would be adding an interface. That’s way Class1 will only be dependent on the interface, and not the actual implementation of Class2. Image 4 ilustrates this point.
Instantiation of the actual implementation will take place somewhere else in the code. This is the one of the most important reasons why dependency injection frameworks are being used.
1:  class ClassA  
2:    {  
3:      private readonly ISomeInterface _interfaceImpl;  
4:    
5:      public ClassA(ISomeInterface interfaceImpl)  
6:      {  
7:        _interfaceImpl = interfaceImpl;  
8:      }  
9:    
10:      public int MethodA()  
11:      {  
12:        return _interfaceImpl.MethodB();  
13:      }  
14:    
15:      public void PrintValues()  
16:      {  
17:        _interfaceImpl.PrintValues();  
18:      }  
19:    }  
20:    
21:    interface ISomeInterface  
22:    {  
23:      int MethodB();  
24:      void PrintValues();  
25:    }  
26:    
27:    class ClassB : ISomeInterface  
28:    {  
29:      private int _elementB = 2 + 2;  
30:    
31:      public int MethodB()  
32:      {  
33:        return _elementB;  
34:      }  
35:    
36:      public void PrintValues()  
37:      {  
38:        Console.WriteLine(_elementB);  
39:      }  
40:    }  

What is the reason behind this, you may ask yourselves???……..Change.

When we have the components this separate, then we can have separate implementation of different problem areas. With separate implementation we can change as much as we want without breaking some other greater process that is using it. Furthermore, when you can change components independently, there is nothing stopping you from developing them independently and even deploy them separately.

Law of Demeter

The Law of Demeter (LoD) or the principle of least knowledge is a object-oriented software design principle. In its general form, the LoD is a specific case of loose coupling.

The formal object form of the law can be summarized as:

A method of an object may only call methods of:
  1. The object itself.
  2. An argument of the method.v
  3. Any object created within the method.
  4. Any direct properties/fields of the object.

The conclusion can be summarized in one sentence:
Don’t talk to strangers!
An object A can request a service (call a method) of an object instance B, but object A should not “reach through” object B to access yet another object, C, to request its services. Doing so would mean that object A implicitly requires greater knowledge of object B’s internal structure. Instead, B’s interface should be modified if necessary so it can directly serve object A’s request, propagating it to any relevant subcomponents. Alternatively, A might have a direct reference to object C and make the request directly to that. If the law is followed, only object B knows its own internal structure.

In particular, an object should avoid invoking methods of a member object returned by another method , like for example:
var a = someObject.FirstMethod().SecondMethod();
For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as “use only one dot”. The above example breaks the law where for example:
var a = someObject.Method();
does not. As an analogy(Wikipedia), when one wants a dog to walk, one does not command the dog’s legs to walk directly; instead one commands the dog which then commands its own legs.

The advantage of following the Law of Demeter is that the resulting software tends to be more maintainable and adaptable. Since objects are less dependent on the internal structure of other objects, object containers can be changed without reworking their callers.

my thanks to: http://thebojan.ninja/2015/04/08/high-cohesion-loose-coupling/

Decorator Design Pattern Intro

0

Category : , ,

Decorator Design pattern allows developer to satisfy some SOLID rules:

  • 1) Single Responsibility Principle – Class/Function should do only one task or Class/Function should have only one reason to change.
  • 2) Open Close Principle – Class/Function is open for extension but close for modification.
  • 3) Liskov Substitution type – If type S is derived from Type T then object of Type T can be replaced by object of Type S.


Simple Example of Design Pattern

namespace BasicDecoratorPattern
{
    public class Client
    {
        public Client()
        {
            IBaseService realTimeService = new BasicServiceImplementaion();

            IBaseService basicRealTimeServiceDecorator1 = new Decorator1OnBasic(realTimeService);
            IBaseService basicRealTimeServiceDecorator2 = new Decorator2OnBasic(realTimeService);

            basicRealTimeServiceDecorator1.Print();
            basicRealTimeServiceDecorator2.Print();
        }
    }

    public interface IBaseService
    {
        void Print();
    }

    public class BasicServiceImplementaion : IBaseService
    {
        public void Print()
        {
            Console.WriteLine("Basic Item");
        }
    }

    public class Decorator1OnBasic : IBaseService
    {
        private readonly IBaseService BasicRealTimeService;
        public Decorator1OnBasic(IBaseService service)
        {
            BasicRealTimeService = service;
        }

        public void Print()
        {
            BasicRealTimeService.Print();
            Console.WriteLine("Extra functionality from Decorator ONE");
        }
    }

    public class Decorator2OnBasic : IBaseService
    {
        private readonly IBaseService BasicRealTimeService;
        public Decorator2OnBasic(IBaseService service)
        {
            BasicRealTimeService = service;
        }

        public void Print()
        {
            BasicRealTimeService.Print();
            Console.WriteLine("Extra functionality from Decorator SECOND");
        }
    }
}




my thanks to: http://www.codeproject.com/Articles/872818/How-and-Where-Decorator-Design-Pattern

SOLID: Part 3 – Liskov Substitution & Interface Segregation Principles

0

Category : ,

http://net.tutsplus.com/tutorials/php/solid-part-3-liskov-substitution-interface-segregation-principles/

Subtypes must be substitutable for their base types.

SOLID: Part 2 – The Open/Closed Principle

0

Category : ,

To design our modules, classes and functions in a way that when a new functionality is needed, we should not modify our existing code but rather write new code that will be used by existing code.


http://net.tutsplus.com/tutorials/php/solid-part-2-the-openclosed-principle

SOLID: Part 1 – The Single Responsibility Principle

0

Category : ,

http://net.tutsplus.com/tutorials/php/solid-part-1-the-single-responsibility-principle/

Class and module design is highly affected by The Single Responsibility Principle and leads to a low coupled design with less and lighter dependencies. But as any coin, it has two faces. Excessive SRP consideration can easily lead to premature optimization and instead of a better design, it may lead to a scattered one where the clear responsibilities of classes or modules may be hard to understand

Introduction to CQRS

0

Category :

http://www.codeproject.com/Articles/555855/Introduction-to-CQRS

CQRS (Command Query Responsibility Segregation, http://martinfowler.com/bliki/CQRS.html) is a technique that separates data creation and modification from data querying. In a pure CQRS model a stored procedure would not both insert/update data and then retrieve data. Those are two distinct operations, and therefore separated.

Ok, I’ll do want to acknowledge that CQRS can complicate your application infrastructure, and that it does not make sense to use this pattern in any and every application you ever build. This is a pattern you would use when you have requirements for Resilience or massive scale.

http://www.sswug.org/editorials/readed.aspx?id=3004

N-Tier Architecture and Tips

0

Category :

Overview

N-Tier architecture is an industry-proved software architecture model, suitable to support enterprise-level client/server applications by resolving issues like scalability, security, fault tolerance and etc. .NET has many tools and features, but .NET doesn’t have pre-defined ways to guard how to implement N-Tier architecture.

N-Tier Architecture Introduction.

Tier and Layer

Firstly we need to clarify the difference between two terms in N-Tier architecture: tier and layer. Tier usually means the physical deployment computer. Usually an individual running server is one tier.
By contrast, layer usually means logic software component group mainly by functionality; layer is used for software development purpose.
Each layer may run in an individual tier. However, multiple layers may also be able to run in one tier.
there's more...

Tier and Process

If a layer can run in an individual process, usually it will also be able to run in an individual computer (tier), hence it can be considered capable for an individual tier in N-Tier architecture. However, this isn’t always true, if there are two layers which are implemented to run in two individual processes but they communicate in a such way that their IPC (inter-process communication) is solely based on a non-distributed way, such as the local shared memory, then these two layers can run in two different processes only in the same computer, not in two different computers.

Layer and Process

A layer may run in an individual process; several layer may also run in an individual process; a layer may run in several processes too. If you read above section “Tier and Layer Relationship”, you can understand here easily.

3-Tier Architecture

The simplest of N-Tier architecture is 3-Tier which typically contains the following software component layers: presentation layer, application layer and data layer, which are depicted below.





A layer can access directly only the public components of its directly-below layer. For example, presentation layer can only access the public components in application layer, but not in data layer. Doing so can minimize the dependencies of one layer on other layers. This dependency minimization will bring benefits for layer development/maintenance, upgrading, scaling and etc. Doing so also makes the tier security enforcement possible. Finally, doing so can also avoid cyclic dependencies among software components.

In order to claim a complete 3-Tier architecture, all three layers should be able to run in separate computers.

These three layers are briefly described as below:
Presentation layer: a layer that users can access directly, such as desktop UI, web page and etc. Also called client.
Application layer: this layer encapsulates the business logic (such as business rules and data validation), domain concept, data access logic and etc. Also called middle layer.
Data layer: the external data source to store the application data, such as database server, CRM system, ERP system, mainframe or other legacy systems and etc. The one we meet often today is database server. For N-Tier architecture, we need to use the non-embedded database server, such as SQL server, Oracle, DB2, MySQL or PostgreSQL. The non-embedded database server can be run in an individual computer. Whereas, the embedded type databases, such as Microsoft access, dbase and etc, cannot run in an individual computer, and then cannot be used as the data layer of the 3-Tier architecture.

1, 2, 3 or More Tier Architecture

1-Tier: all above layers can only run in one computer. In order to achieve 1-Tier, we need to use the embedded database system, which cannot run in an individual process. Otherwise, there will be at least 2-Tier because non-embedded databases usually can run in an individual computer (tier).
2-Tier: either presentation layer and application layer can only run in one computer, or application layer and data layer can only run in one computer. The whole application cannot run in more than 2 computers.
3-Tier: the simplest case of N-Tier architecture; all above three layers are able to run in three separate computers. Practically, these three layers can also be deployed in one computer (3-Tier architecture, but deployed as 1-Tier).
N-Tier: 3 or more tiers architecture. Diagram 2 below depicts a typical N-Tier architecture. Some layers in 3-Tier can be broken further into more layers. These broken layers may be able to run in more tiers. For example, application layer can be broken into business layer, persistence layer or more. Presentation layer can be broken into client layer and client presenter layer. In diagram 2, in order to claim a complete N-Tier architecture, client presenter layer, business layer and data layer should be able to run in three separate computers (tiers). Practically, all these layers can also be deployed in one compute (tier).





Below are brief summaries on all layers in Diagram 2:
Client layer: this layer is involved with users directly. There may be several different types of clients coexisting, such as WPF, Window form, HTML web page and etc.
Client presenter layer: contains the presentation logic needed by clients, such as ASP .NET MVC in IIS web server. Also it adapts different clients to the business layer.
Business layer: handles and encapsulates all of business domains and logics; also called domain layer.
Persistence layer: handles the read/write of the business data to the data layer, also called data access layer (DAL).
Data layer: the external data source, such as a database.

Advantages and Disadvantages of Different Tier Architectures

1 or 2-Tier

Advantages: simple and fast for a lower number of users due to fewer processes and fewer tiers; low cost for hardware, network, maintenance and deployment due to less hardware and network bandwidth needed.
Disadvantages: will have issues when the number of users gets big; as limitation to solve issues like security, scalability, fault tolerance and etc because it can be deployed in only 1 or 2 computes.

N-Tier Architecture

Advantages: the following are general advantages:


loads of dis/advantages and tips can be found on the excellent article this is based on:
http://www.codeproject.com/Articles/430014/N-Tier-Architecture-and-Tips


Code First Approach using EF, IoC, Unity Framework, Repository and UoW Patterns, and MVC Razor View.

0

Category :

Architectural Overview

CodeFirstData layer (DAL)

The data layer is the class library defining a layer which is responsible for interacting with database, contains context classes and a factory pattern implementation to interact with database. The layer contains the repository for each entity to map with database, thus making a complete ORM (Object Resource Model) solution.

CodeFirstEntities layer (POCO Model)

Entity layer acts as a model to MVC application, and is also responsible for the creation of DataBase objects when the dbset is first executed. It contains Entity classes in POCO form, having relations and data annotations(Rules/Constraints to be put on Database table/columns).

CodeFirstServices layer (BLL)

The layer contains services which uses repositories to fetch data from database. The interaction between Services and Repositories is kept loosely coupled thus implementing Inversion of Control using Dependency Injection. Its "constructor based" dependency injection does not allow service to make direct instance of our repositories. Service layer acts as an interface between controllers and repositories, passes request of controller to repositories.

Service Layer defines an application's scope and its available set of operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coordinating responses in the implementation of its operations.

IOC and DI

Dependency Injection is an important component in my application. All the services are required to be late bound with Model layer with Dependency Injection. In addition, the IoC container manages the lifetime of service objects. For example the Context object. I set lifetime type as PerThreadLifetimeManager in Unity configuration. This makes one and only one context object created in a single request and the different request has a different context object. Another thing I want to mention is ASP.NET MVC3 has its own way to provide Dependency Inject for controller via implementing DependencyResolver interface. The IoC container I used in the demo is Unity.

Container

The "Container" or "IOC Container" is the main object that is used to create objects and inject dependencies into them. Whenever you want an object to be open to IoC, you have to use the container to create the instance using container.Resolve<T>() method instead of the "new" keyword.

my thanks to: http://dotnetslackers.com/articles/aspnet/Code-First-Approach-using-Entity-Framework-4.aspx

Inversion of Control/Dependency Injection

0

Category :

Dependency injection is also known as “Inversion of Control,” as originally described by Robert Martin.  Interestingly enough, the development community typically uses the phrase “dependency injection” when talking about the technique itself and “IoC” when talking about dependency injection containers. But rest assured, there is no difference whatsoever between “Dependency Injection” and “Inversion of Control (IoC).”

Dependency Injection - Enables loosely coupled/dependent apps.
You inject a class's dependencies into it, through a constructor or a series of setters, rather than instantiating them in the class. It can be done WITHOUT an IoC container.

Tightly/Highly Coupled Dependencies

HomeController is tightly coupled/dependent on the Employee class, without the Employee class its not much use...
public class HomeController : Controller
{
    public ActionResult Index()
    {
        Employee employee = new Employee();

        return View();
    }
}
Still tightly coupled to the Employee class...
public class HomeController : Controller
{
    private readonly Employee _emp;

    public HomeController(Employee emp)
    {
        this._emp = emp;
    }

    public ActionResult Index()
    {
        ViewBag.Message = _emp.GetName();

        return View();
    }
}

Loosely Coupled Dependencies

Using an Interface allows us to pass any object that implments this Interface, this allows us to pass fake objects which makes Testing easier...
public class HomeController : Controller
{
    private readonly IEmployee _emp;

    public HomeController(IEmployee emp)
    {
        this._emp = emp;
    }

    public ActionResult Index()
    {
        ViewBag.Message = _emp.GetName();

        return View();
    }
}
There are three main styles of dependency injection

Constructor injection.

Passing an object's dependencies to its constructor.
examples above

Setter injection.

Dependencies are set onto public properties exposed by the object in need. Dont need to modify the constructor of a legacy class.
Allows expensive resources or services to be created as late as possible and only when needed.
Should be used sparingly in place of Constructor Injection, because it:
Does not make it clear to the developer which dependencies are needed when, at least until a "has not been initialized" exception is thrown.
Makes it a bit more difficult to track down where the exception came from and why it got thrown.

Interface injection.

seems to be very similar to Controller Injection above, good description, http://www.martinfowler.com/articles/injection.html
The third injection technique is to define and use interfaces for the injection. With this technique you define an interface that you use to perform the injection through. This configuration has two stages, registering components through lookup keys is pretty similar to the other examples. A new step is to register the injectors that will inject the dependent components. Each injection interface needs some code to inject the dependent object.

Injection Options (Injectors)

The next logical question is, what actually creates the dependencies that are to be injected into "injectees"? There are two appropriate places for adding creation logic: controllers and containers.

Manual Injection/DI Controllers

This requires the HomeController to be instantiated somewhere and dependencies supplied using constructor injection, which I presume is not  an easy option with MVC.
Regardless of what you use as your controller, the controller is an appropriate location for performing Dependency Injection "wiring". This is where concrete objects are created and injected as dependencies.

Automatic Injection/DI Container

Inversion-of-Control/Dependency-Injection "Containers" can be used to watch an application and inject dependencies whenever a particular event occurs. For example, whenever a HomeController instance is created, it automatically gets injected with its needed dependencies.

Dependency injection involves at least three elements:

1) a dependent consumer - HomeController
2) a declaration of a component's dependencies, defined as interface contracts - Constructor
3) an injector (sometimes referred to as a provider or container) that creates instances of classes that implement a given dependency interface on request - IoC container/manually.

Inversion of Control (also known as the Hollywood Principle - "Don't call us, we'll call you").

Inversion of Control is a key part of what makes a framework different to a library. A library is essentially a set of functions that you can call, these days usually organized into classes. Each call does some work and returns control to the client.
A framework embodies some abstract design, with more behavior built in. In order to use it you need to insert your behavior into various places in the framework either by subclassing or by plugging in your own classes. The framework's code then calls your code at these points.
One simple example of IoC is JUnit, the framework code calls setUp and tearDown methods for you to create and clean up your text fixture. It does the calling, your code reacts/implements the creation and clean up - so again control is inverted.

Inversion of Control Containers

For this new breed of IoC containers the inversion is about how they lookup a plugin(IEmployee) implementation. The approach that these containers use is to ensure that any user of a plugin follows some convention(an interface) that allows a separate assembler module to inject the implementation into the lister(HomeController).
As a result I think we need a more specific name for this pattern. Inversion of Control is too generic a term, and thus people find it confusing. As a result with a lot of discussion with various IoC advocates we settled on the name Dependency Injection.
There is some confusion these days over the meaning of inversion of control due to the rise of IoC containers; some people confuse the general principle here with the specific styles of inversion of control (such as dependency injection) that these containers use.

Using a Service Locator

The key benefit of a Dependency Injector is that it removes the dependency that the HomeController class has on the concrete Employee implementation. Injection isn't the only way to break this dependency, another is to use a service locator.
The basic idea behind a service locator is to have an object that knows how to get hold of all of the services that an application might need, needs to be investigated further...

Service Locator vs Dependency Injection

The fundamental choice is between Service Locator and Dependency Injection. The first point is that both implementations provide the fundamental decoupling that's missing in the naive example - in both cases application code is independent of the concrete implementation of the service interface. The important difference between the two patterns is about how that implementation is provided to the application class. With service locator the application class asks for it explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class - hence the inversion of control.


my thanks to:
http://www.martinfowler.com/articles/injection.html http://en.wikipedia.org/wiki/Dependency_injection
http://www.codeproject.com/Articles/13831/Dependency-Injection-for-Loose-Coupling
http://devlicious.com/blogs/billy_mccafferty/archive/2009/11/09/dependency-injection-101.aspx