Basic programming, .NET technology.

2 - [Updated] - ASP .Net core - Fundamentals - Dependency injection

 This series is a collection of knowledge about ASP .NET Core. It just is my notes.

Part 1: Startup file in ASP .Net core.

Part 3: Middleware.

Part 4: Host and Servers.

Part 5: Configurations.

Part 6: Environment.

Part 7: Logs.

Part 8: Error Handling.

Part 9: Routing.

Part 10: Make an HTTP Request.

Part 11: Static files.

Part 12: Authentication and Authorization.

Part 13: CORS.


    In this note, I want to summary some knowledge about DI in Asp.net core.



First, DI is to archive Inversion of Control, solid principle.
We have 3 types of DI: constructor injection, method injection, property injection

The built-in DI of the .net core base on constructor injection.

a. How to register services
  • Register a service in method 'ConfigureServices'
  • Use the "services.Configure" method to config/binding  our configuration to option
  • also can create an extension method of IServicesCollection to compute a group of related service
    • Note: convention : Add{OurServiceName}, for example: AddDataAcessLayer, AddBusinessServices...

b. Service lifetime
  • Transient: short lifetime, create when  service container request, disposed at the end of the request
  • Scoped: create per client request, AddDbContext for example.
  • Singleton: create at the first time that they're requested; disposed of an object only when app shutdown, should consider if we use it, since memory performance

c. Design service for dependency injection
When designing services for dependency injection:
  • Avoid stateful, static classes and members. Avoid creating a global state by designing apps to use singleton services instead.
  • Avoid use Service Locator anti-pattern.
  • Avoid direct instantiation of dependent classes within services. Direct instantiation couples the code to a particular implementation.
  • Make services small, well-factored, and easily tested.
d. Dispose of services: Container takes this responsibility

e. Keyed Service (From ASP.NET Core 8)
When using keyed services:
  • Have an interface with multiple implementations
  • And need to use one of those implementations in different places in your application
Add services by using: AddKeyedSingleton (or AddKeyedScoped or AddKeyedTransient)

builder.Services.AddKeyedSingleton<ICache, BigCache>("big");
builder.Services.AddKeyedSingleton<ICache, SmallCache>("small");

Access a registered service by specifying the key with the [FromKeyedServices]

[HttpGet("big-cache")]
public ActionResult<object> GetOk([FromKeyedServices("big")] ICache cache)
{
    return cache.Get("data-mvc");
}


Ref:
Share:

1 - [Updated] - ASP .Net core - Fundamentals - Startup

 This series is a collection of knowledge about ASP .NET Core. It just is my notes.

Part 2: Dependency Injection. 

Part 3: Middleware.

Part 4: Host and Servers.

Part 5: Configurations. 

Part 6: Environment.

Part 7: Logs.

Part 8: Error Handling.

Part 9: Routing.

Part 10: Make an HTTP Request.

Part 11: Static files.

Part 12: Authentication and Authorization.

Part 13: CORS.

I take some notes for the startup file in Asp .net core:

  • Specified when app host is built.
  • ConfigureServices method:
    • called by the host before Configure method
    • Use to set up services for app
    • There is some build-in extension method (AddDbContext, AddEntityFrameworkStores..)
    • Usually used to add business services/ DAL class to dependency injection.
      • You can write an extension method on IServiceCollection to add more services as you want.
  • Configure method
    • used to specify how the app responds to an HTTP request.
    • to configure adding  middleware component to IApplicationBuilder
    • there are some extension methods to  add middleware
    • You can write a new extension method by using IApplicationBuilder  (Ex: write custom middleware)
    • How to write custom middleware
  • Multiple startups
    • for different environments.
    • suffix name matched with the current environment is prioritized, for example (StartupDevelopment)
  • [Updated] - ASP.NET Core 6+
Startup code in the program file because of the minimal hosting model.

  var builder = WebApplication.CreateBuilder(args);
    // Add services to the container.
    builder.Services.AddRazorPages();
    builder.Services.AddControllersWithViews();
    // You can add your user-defined services here
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    // You can add your custom middle ware here
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    ...
    app.Run();


References:

[Microsoft Learn] - App startup in ASP.NET Core

    Share:

    Abstract class và Interface (1)

    We all know the pillars for object-oriented programming are: abstraction, inheritance, encapsulation, polymorphism. The motto is like that, but in an old programming language like C#, how do you apply it to a real problem. Bờm researched and learned, today he understood two keywords: abstraction and inheritance. In this "Hoa Son commentary on the code", Bờm presented: What is an abstract class? What are interfaces?

    1. Abstract class. So we can say that an abstract class cannot have an instance (a concrete object, an instance). Abstract classes are often used to define base classes in inheritance.
    In an abstract class, we can define abstract methods or non-abstract methods.

    A small example will make it easier to understand:
    We define 2 classes: Dog and Cat


    We see that both the Dog and Cat classes share the same properties and methods. We wonder if there is a way to collect common properties and methods? OOP shows that: we can apply abstraction, and inheritance in this case. We abstract the two classes Dog and Cat into an Animal class with common properties and methods, using the abstract keyword to do this.

    The Animal class will be declared as follows



    Refactor Dog and Cat class by using inheritance.


    Through this example, we need to remember:
    - Use abstract class to achieve abstraction, inheritance in object-oriented programming
    - Use the abstract keyword to declare a class or a method as abstract.
    - To implement abstract members of an abstract class, we use the keyword "override" in a subclass.

    2. Interface. We all know C# supports inheritance, but a class can only inherit from one superclass (single inheritance). It does not support multiple inheritances. To solve this problem, we can use an interface. 

    In the subclass, we implement the interface. A subclass can implement many different interfaces. So what is an interface?

    The interface is like a class, can contain methods, properties ... interface contains only declarations (declaration). The classes implement the interface, which will specify the methods and properties of that interface.

    Going back to the above example, we analyze that between the two classes Dog and Cat have their own actions, for example, dogs can bite (bite)... if we declare a common method (Bite) in the abstract class: animal, then we must apply this method to the Cat class (which is not reasonable).

    We could also define a Bite method for the Dog class only, but think further... some other animals have the ability to "bite" too, and we want to abstract this method so we can use it in subclasses (if necessary), in this case, we use interface.

    We can declare an interface like this: We all know C# supports inheritance, but a class can only inherit from one superclass (single inheritance). It does not support multiple inheritances. To solve this problem, we can use an interface. In the subclass, we implement the interface. A subclass can implement many different interfaces. So what is an interface?

    We can declare an interface like this:


    The Dog class implements the interface, here we also see that: by using the interface, the Dog class can realize the dream of multiple inheritances.


    So:
    - Use interfaces for multiple inheritances.
    - Use interfaces to achieve abstraction in OOP.
    - In addition, the use of interfaces also reduces dependencies between classes. Applied to achieve at a theory called "Solid" that you study about programming principles, the design pattern has probably been heard.

    In this article, Mr. Bom only introduces abstract classes and interfaces, the simplest way to achieve two pillars in object-oriented programming is abstraction and inheritance. The problem about using the interface in a more advanced form, to reach the solid programming principle, it lies in another realm... see you in the next "Hoa Son discussion of code".
    Share:

    Data type 3 - string type

    In any programming language, to represent the value of a variable, we need to declare the data type of that variable. 
    In previous lessons, Bờm reviewed value types and reference types. Following that series, Bờm wrote something about a data type that we also use a lot to process strings, which is String. So what do we know about string type in C# language? With limited knowledge, I will only point out a few basic points about strings as a way to review.

    Yeah, let's go:

    1. What is String? string and System.String are the same or different?
    For string processing .Net framework provides us with a class: System.String (fields, methods, constructor...). A String in C# is an object of type String, its value is text. This means that if you want to store information of a string, a text, you can completely use string type to store. 

                // String of characters 
                System.String nickName = "Victor";

                // String made of an Integer 
                System.String age = "28";

    Many of you also asked if string and System.String is different or the same, oh good question... When I was a student, I used to ask the same question... And the answer is: in In C#, the keyword string is an alias of String, so the two notes string and String are basically the same. In programming you want to use string or String keyword, it's up to you!!!

    2. String is an immutable.
    This means you can't change the string once it's created.

    For example:
              string string1 = "Hello World!!";

    It will occupy a memory area on the heap to store this string.

    If you want to change the value of string1 by adding to string1 the value "from Tutorials teacher". You think: the system just needs to change the value of string1 by adding the value "from Tutorials teacher" and it's ok...

    Oh No, because of its immutable nature, it will create a new string "Hello!! from tutorials teacher" and assign this value to string1.
    (image: string_memory; source: tutorialteacher.com)

    Unprecedented magic and this magic brings a disadvantage that if we modify the string1 many times, it also creates many new strings, result in reduced program performance.

    To solve this problem, C# martial arts secrets give us a spell String "Biu Do".

    3. String Builder
    String builder helps to increase performance when working with string type when we need to edit, delete, or any operation on string. It increases performance because each time it manipulates a string, it doesn't create any new strings, simply manipulates the string itself.


    (image: stringbuilder_memory; source: tutorialteacher.com)

    Let see the below example:

    Yup!! Here's the result, surprise!!!


    In short, string builder is useful when working with string concatenation and string operations, it can increase performance when manipulating strings.

    When working on strings, we need to call methods or apply operations on them. So what happens when our string variable has a value of null.

    4. Null string in C#
    A null string is a variable of type string but it is uninitialized or has a value of null.
    If we call a property or a method on a null string, boom.... an exception will be thrown... This makes us think, to get the best handling code. A small note, but martial.

    use the method: IsNullOrEmpty

    The above is just a little basic theory about string so that we have the concept of null string, what is an immutable string? how to solve performance problems when working with strings... There are many things about strings, such as helper methods, properties, fields... I think the basic knowledge of what string is, string is immutable it needs to be stored in our memory before we find a way to apply it to real string processing problems.

    Related Posts:

    Share:

    DATA STRUCTURES - 1


    Data structures and algorithms – the nightmare of most IT students. After finishing school, I, as well as my fellow students, confidently declared that: He knows us, and we don't know them. Therefore, this series of articles on "Data Structures and Algorithms" was born, the purpose is to help me review my knowledge of data structures and algorithms.

    What is data structure? It is a technique for organizing and arranging data in a computer's memory. How data is sorted and organized affects how it is retrieved and used. Imagine that the memory of your computer is just your tiny attic… and the data is the items in your home, how you organize those items will affect how you find them and use them. they.

    In this article, we will learn about: Arrays (Array). Shall we know what they are? Performance and how to use them?

         1. Array
    A collection of data elements stored contiguously in a memory area. The elements of a must have the same data type (data type). Array elements can be accessed directly based on the index. In .Net Framework, the index starts from 0.

    Consider the following example:

    Statement 1: We declare an array of type integer
    Statement 2: We initialize the array with 4 elements.
    The allocation and initialization of memory to store the array will happen as shown below.

    To work with arrays we need to know 2 types of common operations: Allocate and access.
    - Allocate: this is the declaration and initialization of the array, it will allocate a memory area on the stack when we declare the array and a memory area on the heap when we initialize the size of the array.
    - Access: to access any element of the array, we use index. As said .Net Framework starts from 0. With the following code, we assign the value to the 2nd element and retrieve its value to use.

    The elements of the array are stored contiguously in a block of memory, and it is accessed directly through the index of the array. That's why reading and writing arrays is fast. However, the array requires a size declaration when initialized, and its elements must be of the same data type.

    To decide whether to use arrays in programming or not, we need to consider three issues: do we require fast data access or do we need to be fast? Is it possible to know in advance the number of elements in a data set? And is the data type of the elements the same?

    However, we can use ArrayList to replace Array in case the size of the array cannot be fixed or the datatype of the element is different.

    Share:

    Lập trình hướng đối tượng – OOP (2)

    In my previous article, I shared some of its basic concepts: what is an object? What are classes? How is the constructor defined and used?

    Next, in this article, I will present the basic features of object-oriented programming. Everyone knows when it comes to object-oriented programming, any coder, from amateur to professional, must master these characteristics. It's like the inner gong of a sect. Referring to that type of martial arts, one must immediately remember its inner gong and know how to use it. So what is the inner work of the mind of OPP? These are Abstraction, Inheritance, Encapsulation, Polymorphism.

    Here we go.

    First, Abstraction: It is a feature, an object-oriented principle, used to describe and display the necessary features of an object for other objects. This feature allows hiding the details of the object. It focuses on what the object does rather than how the object does it.

    You can picture it like this: We have a dog, it is an object. It has action: go and eat. Dogs also have a way of walking, a dog's way of eating is different from a cat's. Abstraction, describing to the surrounding, the dog has the act of eating and walking. But how to eat, how to walk it is the dog's business, not to be described to the surroundings.
    See the following code for more clarity.


    Second, Encapsulation.
    This means that the details of an object are restricted from being accessed by other objects, or hidden from view by other objects.
    Speaking of closures, we need to know a concept called access modifier. It controls access to member data in a class. We have access modifiers: private, public, internal, protected, protected internal.

    - Private: only members of the same class can access it.
    - Public: unlimited access.
    - Protected: only members of the class and the derived class have access.
    - Internal: only members in the same assembly.
    - Protected internal: members in the same assembly or inherited class are accessible.




    Next, let's learn the third, Inheritance.
    Defining inheritance in the object-oriented direction is the same as in social inheritance. Everyone must know who inherits, inherits from whom, and inherits what characteristics?
    In object-oriented, the class to be inherited is called “superclass” or “base class”, in this class we define common features that will be inherited from subclasses. Subclasses that inherit from the parent class are called "derived classes".
    The benefit of inheritance is that it can reuse code, increase system maintainability, as well as reduce the cost of system development. C# does not support multiple inheritances, to do that, we can use an interface.
    An example of inheritance: We have a superclass animal: has a name property, a constructor, a move and eat method. Subclasses: dog, cat inherit from an animal class.



    Implement base class



    Implement derived class: Dog



    Use derived class:

                    



    Finally Polymorphism.
    Polymorphism means many forms. When a problem is handled in different ways, we call it polymorphism. We have two types of polymorphism: Compile polymorphism, or overloading, and run-time polymorphism, or overriding.
    -  Overloading: a method has many different forms based on its own parameters.



    - Overriding by using the keyword: virtual and override
    -        



    Above, you and I have gone through the 4 main slogans in object-oriented programming. Hopefully, we will memorize and use it in the best way in the Kung-fu code.

    Related posts:
    Share:

    Lập trình hướng đối tượng - OOP 1


    If you are a student or a professional coder, you must have heard many times about OPP or object-oriented programming.
    In my series of 2 articles, I will review the basic concepts of object-oriented programming. What is it? What are its characteristics?

    OPP stands for Object oriented programming. It is a programming paradigm that is based on objects. It models real-world objects into programming objects. Those objects have the same properties and actions as in the real world. 

    For example, A student is a real-world object. Student attributes height, weight, age, name... Actions: eat, sleep, walk, study. When modeled in programming, we also have an object that holds the data of student information and actions.
    So each student object we create a student object in programming? It's not like that: We have concepts: object and class
    What are classes?
    It is a prototype of objects. It has variables that store data as well as methods of an object

    We have a student class as follows


    Object là gì?
    Object là một thể hiện cụ thể của một đối tượng thực tế thông qua bản mẫu là một class. Khi một object được tạo thì nó sẽ được cấp phát một vùng nhớ trên heap để lưu trữ thông tin của nó.
    Ví dụ: Ta có đối tượng sinh viên 1 là một thể hiện cụ thể của một sinh viên trong thực tế, qua bản mẫu là class sinh viên ta vừa tạo ở trên.

    What are Objects?
    The object is a concrete instance of an actual object through the template is a class. When an object is created, it will be allocated a memory area on the heap to store its information.

    For example, We have student object 1 which is a specific instance of a student in reality, through the template is the student class we just created above.



    Here we create a constructor with 2 variables passed in, name and age. This constructor will assign values to the member variables of the class.
    When we initialize the student object with this constructor, we will pass the value of name, age.



    Example: 

    Using the student class creates a student object, and calls the object's self-introduction function.


    Results: Just like in the real world, students use their own information to introduce others, in programming when abstracting an object, it also has the same behavior: using the information to self-identify. introduce yourself


    Through this example, we can better understand: what is a class? What is an object? What is Constructor? And how to use them. In the following article, I will present the basic properties of OPP.

    Related posts:
    Share:

    Featured Posts

    Data type 3 - string type