European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core Hosting - HostForLIFE :: Dependency Injection And Service Lifetime in ASP.NET Core

clock September 19, 2023 08:34 by author Peter

Dependency injection is a technique for getting a dependant object from somewhere other than the class that was created with the new keyword.

Pros

  • It improved modularity.
  • It boosts testability.
  • Place the dependent in a central location.
  • Uncouple the system

The dependency injection (DI) software design pattern, which is a mechanism for accomplishing Inversion of Control (IoC) between classes and their dependencies, is supported by ASP.NET Core.

  • Constructor Injection: The most common method of injecting dependencies into a class by giving them as constructor parameters.
  • Method Injection is the process of injecting dependencies into a method as parameters.
  • Property Injection is the process of populating a class's properties with the necessary dependencies.

We must provide the dependency's lifespan when we register it with DI Container (IServiceCollection).

Service Duration
The service lifetime determines how long an object lives once it is generated by the container. When registering, use the following method on the IServiceColletion to create the lifetime.

  • Services are transient since they are produced each time they are requested.
  • For example, with transitory tea makers, each customer gets a different tea. They get a one-of-a-kind tea experience because a new tea maker arrives for each order and serving.
  • Services are created just once per request.
  • In a teashop, for example, scored tea makers are equivalent to having one tea maker assigned to each table or group, giving the same type of tea to everyone within the group. When a new group arrives, they are assigned a tea maker.
  • Singleton: A service is created only once for the duration of the program. For example, having a singleton tea maker in a teashop is equivalent to having a renowned tea master who provides the same tea to every customer. This tea master is constantly there, remembers all orders, and regularly serves everyone the same tea.

Let's now dive into the code to further explain this concept.

TeaService
public class TeaService : ITeaService
{
        private readonly int _randomId ;
        private readonly Dictionary<int, string> _teaDictionary = new()
        {
            { 1, "Normal Tea ☕️" },
            { 2, "Lemon Tea ☕️" },
            { 3, "Green Tea ☕️" },
            { 4, "Masala Chai ☕️" },
            { 5, "Ginger Tea ☕️" }
        };
 public TeaService()
 {
      _randomId = new Random().Next(1, 5);
  }
  public string GetTea()
   {
      return _teaDictionary[_randomId];

    }
}
public interface ITeaService
{
        string GetTea();
}

RestaurantService: which injects TeaService.
public class RestaurantService : IRestaurantService
{
        private readonly ITeaService _teaService;
        public RestaurantService(ITeaService teaService)
        {
            _teaService = teaService;
        }

        public string GetTea()
        {
            return _teaService.GetTea();
        }
}
public interface IRestaurantService
{
     string GetTea();
 }

Tea Controller: which is injecting TeaService and RestaurantService.
[Route("api/[controller]")]
[ApiController]
public class TeaController : ControllerBase
{
  private readonly ITeaService _teaService;
  private readonly IRestaurantService _restaurantService;

  public TeaController(ITeaService teaService,
   IRestaurantService restaurantService)
  {
      _teaService = teaService;
      _restaurantService = restaurantService;
   }

   [HttpGet]
   public IActionResult Get()
   {
      var tea = _teaService.GetTea();
      var teaFromRestra = _restaurantService.GetTea();
      return Ok($"From TeaService : {tea}
               \nFrom RestaurantService : {teaFromRestra}");
    }
}


Register services to DI Container.

a. Transient
// Add the below line to configure service in Statup.cs
services.AddTransient<ITeaService, TeaService>();
services.AddTransient<IRestaurantService, RestaurantService>();


Output

b. Scoped
// Add the below line to configure service in Statup.cs
services.AddScoped<ITeaService, TeaService>();
services.AddScoped<IRestaurantService, RestaurantService>();


Output

c: Singleton
// Add the below line to configure service in Statup.cs
services.AddSingleton<ITeaService, TeaService>();
services.AddSingleton<IRestaurantService, RestaurantService>();


Output

HostForLIFE ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



European ASP.NET Core Hosting - HostForLIFE :: Pattern Matching in C# for Simplifying Code

clock September 11, 2023 08:50 by author Peter

Pattern matching is a functional programming feature that is already present in several prominent languages, including Scala, Rust, Python, Haskell, Prolog, and others. It is used to test expressions for certain circumstances while also testing the kinds.

It enables you to check if a value matches a specific pattern and then execute code based on that match in an efficient and simple manner. This capability is very handy when working with complex data structures like collections and when simplifying conditional expressions.

Pattern Matching was introduced in C# 7.

Benefits- Patterns Matching

  • Type-Testing
  • Nullable-type checking
  • Typecasting and assignment
  • High readability
  • Concise syntax Less convoluted code.


Usages

Pattern matching can be used in 2 places.
'is' expressions
'switch' expressions

Patterns Matching Types through C# Versions

C# 7
Type Pattern
Declaration Pattern
Constant Pattern
Null Pattern
Var Pattern

C# 8
Property Pattern
Discard Pattern
Positional Pattern
Discard Pattern

C# 9
Type Pattern
Relative Pattern
Logical Pattern (Combinators)
Negated Null Constant Pattern
Parenthesized Pattern

C# 10
Extended Property Pattern

C# 11
List Pattern

Type Pattern
A type pattern in C# allows you to check whether an object is of a specific type and, if it is, cast it to that type while declaring a new variable.

using System;

public class Program
{
    public static void Main()
    {
        object someObject = "Hello, World!";

        if (someObject is string stringValue)
        {
            // stringValue is now a strongly-typed variable of type string
            Console.WriteLine($"Length of the string: {stringValue.Length}");
        }
        else
        {
            Console.WriteLine("someObject is not a string.");
        }
    }
}

Pattern of Declaration
In C#, a declaration pattern is one that not only examines whether an expression matches a given pattern but also declares a new variable with the matched value. This pattern is frequently used in conjunction with is expressions to accomplish pattern matching as well as variable declaration in a single action.

C# 7.0 added declaration patterns, which provided a handy approach to simplify code.

using System;

public class Program
{
    public static void Main()
    {
        object someObject = 42;

        if (someObject is int intValue)
        {
            // intValue is now a strongly-typed variable of type int
            Console.WriteLine($"The value is an integer: {intValue}");
        }
        else
        {
            Console.WriteLine("The value is not an integer.");
        }
    }
}

Recurring pattern
Testing against a constant value, which can be an int, float, char, string, bool, enum, const-declared field, or null.
It's frequently used in switch statements and pattern-matching contexts to conduct different actions based on an expression's value.

using System;

public class Program
{
    public static void Main()
    {
        object someObject = 42;

        if (someObject is int intValue)
        {
            // intValue is now a strongly-typed variable of type int
            Console.WriteLine($"The value is an integer: {intValue}");
        }
        else
        {
            Console.WriteLine("The value is not an integer.");
        }
    }
}


Null Pattern
Check if a reference or nullable type is null.
It is particularly useful for safely handling null values and reducing null reference exceptions.
Null pattern matching was introduced in C# 9.0 as part of the language's pattern-matching enhancements.

Var Pattern
Similar to the type pattern, the var pattern matches an expression and checks for null, as well as assigns a value to the variable.

The var type is declared based on the matched expression’s compile-time type.

using System;

public class Program
{
    public static void Main()
    {
        object someObject = (42, "Hello, Peter!");

        if (someObject is var (number, message) && number is int && message is string)
        {
            Console.WriteLine($"Number: {number}, Message: {message}");
        }
        else
        {
            Console.WriteLine("Pattern match failed.");
        }
    }
}


Property Pattern
Property pattern matching in C# is a feature that allows you to match objects based on the values of their properties or fields.
It simplifies code by enabling you to specify patterns that involve property values directly in pattern-matching expressions.
Property pattern matching was introduced in C# 8.0 and is a powerful way to work with complex data structures.
using System;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        Person person = new Person { Name = "Alice", Age = 30 };

        if (person is { Name: "Alice", Age: 30 })
        {
            Console.WriteLine("It's Alice, age 30!");
        }
        else
        {
            Console.WriteLine("It's someone else.");
        }
    }
}


Discard Pattern
discard pattern in C# allows you to match a pattern but discard the matched value.
It's represented by the underscore (_) and is especially useful when you want to indicate that you're not interested in the value that matches a pattern, which can help improve code clarity and readability. Discard patterns were introduced in C# 7.0.

using System;

public class Program
{
    public static void Main()
    {
        object someObject = "Hello, World!";

        if (someObject is string _)
        {
            Console.WriteLine("The object is a string, but we're not interested in its value.");
        }
        else
        {
            Console.WriteLine("The object is not a string.");
        }
    }
}


Positional Pattern
Positional patterns in C# allow you to match objects based on the values of their elements in a specific order, making it easier to work with complex data structures like arrays, tuples, or user-defined types.
This feature was introduced in C# 8.0 and provides a concise way to match objects by their elements' positions.

using System;

public class Program
{
    public static void Main()
    {
        Point point = new Point(3, 4);

        string location = DescribePoint(point);

        Console.WriteLine(location);
    }

    public static string DescribePoint(Point point)
    {
        return point switch
        {
            (0, 0) => "The point is at the origin (0, 0).",
            (var x, var y) when x == y => $"The point is on the diagonal at ({x}, {y}).",
            (var x, var y) => $"The point is at ({x}, {y}).",
            _ => "Unknown location."
        };
    }
}

public record Point(int X, int Y);


Tuple Pattern
Tuple patterns in C# allow you to match objects against specific tuple structures. This feature simplifies the process of deconstructing and matching tuples in pattern-matching expressions.
Tuple patterns were introduced in C# 8.0 and make it easier to work with complex data structures involving tuples.

using System;

public class Program
{
    public static void Main()
    {
        var point = (3, 4);

        string location = DescribePoint(point);

        Console.WriteLine(location);
    }

    public static string DescribePoint((int X, int Y) point)
    {
        return point switch
        {
            (0, 0) => "The point is at the origin (0, 0).",
            (_, 0) => "The point is on the x-axis.",
            (0, _) => "The point is on the y-axis.",
            var (x, y) when x == y => $"The point is on the diagonal at ({x}, {y}).",
            var (x, y) => $"The point is at ({x}, {y}).",
        };
    }
}


var person = ("Alice", 30);

var description = person switch
{
    ("Alice", 30) => "This is Alice, age 30.",
    ("Bob", var age) => $"This is Bob, age {age}.",
    _ => "Unknown person."
};

C#
 ‘Enhanced’ Type Pattern

    You can do type checking in switch expressions without using the discards with each type

public string CheckValueType(object value)=> value switch
{
  int => "integer number",
  decimal => "decimal number",
  double => "double number",
  _ => throw new InvalidNumberException(value)
};


Pattern matching is a powerful feature in C# that simplifies code by allowing you to match objects and structures based on patterns. Whether you're checking types, values, or even properties, pattern matching makes your code more concise and readable.

Pattern matching in C# streamlines your code, reduces errors, and enhances readability, making it a valuable tool for developers.

HostForLIFE ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 




European ASP.NET Core Hosting - HostForLIFE :: Using the NavigationPage in.NET MAUI

clock September 5, 2023 08:40 by author Peter

This tutorial will teach us about the NavigationPage in.NET MAUI. If you are new to MAUI, I recommend that you read the articles in this series listed below. One of the most important components of developing an application is navigation. The NavigationPage class in.NET MAUI provides a hierarchical navigation experience for navigating through pages. The navigation is provided as a LIFO (Last-In, First-Out) stack of page objects by NavigationPage. To demonstrate, I'll add three ContentPages to the.NET MAUI project and demonstrate how to navigate from one page to the next. The most frequent page type in.NET MAUI is the ContentPage, which is a single view, and a single.NET MAUI application can contain numerous pages derived from the ContentPage.

Let's create three.NET MAUI ContentPages (XAML) in a.NET MAUI project. I called the three ContentPages HomePage, ProductPage, and ProductDetails page.

A root page is required for every app with several pages. Now, let's make the HomePage the Navigation stack's root page. To accomplish this, we must associate the App.Main page property with the NavigationPage object, which constructor accepts the root page as a parameter, i.e. the App's HomePage.

Now, add a button (named btnGoToProductPage) to navigate from the HomePage to ProductPage.

HomePage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="NavigationPageDemo.HomePage"
             Title="Home Page">
    <VerticalStackLayout>
        <Label Text="Home Page Content"
               VerticalOptions="Center"
               HorizontalOptions="Center"
               Margin="10" />
        <Button x:Name="btnGoToProductPage"
                Text="Go to Product Page"
                Clicked="btnGoToProductPage_Clicked"
                Margin="10" />
    </VerticalStackLayout>
</ContentPage>


A page can be navigated by calling the PushAsync method on the Navigation property of the Current Page. In the below example, ProductPage is pushed onto the Navigation stack where it becomes the active page.

HomePage.xaml.cs
using System;
using Microsoft.Maui.Controls;
namespace NavigationPageDemo
{
    public partial class HomePage : ContentPage
    {
        public HomePage()
        {
            InitializeComponent();
        }
        private void btnGoToProductPage_Clicked(object sender, EventArgs e)
        {
            Navigation.PushAsync(new ProductPage());
        }
    }
}


In ProductPage, I have added two buttons named “btnGoToProductDetails” and ”btnGoBackToHomePage”. On clicking on btnGoToProductDetails, the ProductDetails page will be added to the navigation stack, and it will become the active page. On clicking on btnGoBackToHomePage, the PopAsync method will remove the current page i.e., Product Page, from the navigation stack, and the topmost page of the stack will become the active page.

ProductPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="NavigationPageDemo.ProductPage"
             Title="Product Page">
    <VerticalStackLayout>
        <Label Text="Product Page"
               VerticalOptions="Center"
               HorizontalOptions="Center"
               Margin="10" />
        <Button x:Name="btnGoToProductDetails"
                Text="Go to Product Details"
                Clicked="btnGoToProductDetails_Clicked"
                Margin="10" />
        <Button x:Name="btnGoBackToHomePage"
                Text="Go back to Home Page"
                Clicked="btnGoBackToHomePage_Clicked"
                Margin="10" />
    </VerticalStackLayout>
</ContentPage>

ProductPage.xaml.cs
using System;
using Microsoft.Maui.Controls;
namespace NavigationPageDemo
{
    public partial class ProductPage : ContentPage
    {
        public ProductPage()
        {
            InitializeComponent();
        }
        private void btnGoToProductDetails_Clicked(object sender, EventArgs e)
        {
            Navigation.PushAsync(new ProductDetails());
        }
        private void btnGoBackToHomePage_Clicked(object sender, EventArgs e)
        {
            Navigation.PopAsync();
        }
    }
}

On the ProductDetails Page, I have added a button i.e. btnGoBackToProductPage. On Clicking, it will remove the current page from the navigation stack with the PopAsync method call.

ProductDetails.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="NavigationPageDemo.ProductDetails"
             Title="Product Details">
    <VerticalStackLayout>
        <Label Text="Product Details"
               VerticalOptions="Center"
               HorizontalOptions="Center"
               Margin="10" />
        <Button x:Name="btnGoBackToProductPage"
                Text="Go back to Product Page"
                Clicked="btnGoBackToProductPage_Clicked"
                Margin="10" />
    </VerticalStackLayout>
</ContentPage>


ProductDetails.xaml.cs

using System;
using Microsoft.Maui.Controls;
namespace NavigationPageDemo
{
    public partial class ProductDetails : ContentPage
    {
        public ProductDetails()
        {
            InitializeComponent();
        }
        private void btnGoBackToProductPage_Clicked(object sender, EventArgs e)
        {
            Navigation.PopAsync();
        }
    }
}


Working Preview on Android

Preview on Windows

The navigation property of the page also provides the InsertPageBefore and RemovePage methods for manipulating the Stack by inserting the pages or removing them.

.NET MAUI also supports Modal navigation. A modal page encourages users to complete a self-contained task that cannot be navigated away until the task is completed or canceled. PushModalAsync and PopModalAsync are the methods to push and pop pages from the modal stack.

NavigationPage has several properties; a few are listed below. (For more details, you can refer to the documentation on Microsoft's official website)
1. BarBackgroundColor: Specifies the background color of the Navigation Bar.
2. BarTextColor: Specifies the Text color of the Navigation Bar
3. HasNavigationBar: Specifies whether a navigation bar is present on the NavigationPage. Its default value is true.
4. HasBackButton: Represent whether the navigation bar includes the back button. The default value of this property is true.

Let’s try to change the navigation bar and text color. Use the below code in the App class; we can change the BarBackground and BarTextColor.


Preview on Android

Preview on Windows


HostForLIFE ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.


 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in