Tuesday, 3 December 2024

What is Params In C#?

Leave a Comment

When working with methods that accept a variable number of the same type of parameters, the "params" keyword is essential for increasing flexibility and ease in C# programming.


C# parameters

This feature, which enables developers to send an arbitrary number of parameters or optional parameters of the same type in a method declaration, is especially helpful when the precise number of arguments is unknown in advance.

class Program
{
    public static void AddItemsToShoppingBasket(params string[] items)
    {
        // ....
    }

    public static void AddItemsSumToShoppingBasket(params int[] sum)
    {
        // ....
    }
}

Here, we do not know the count of items beforehand, and the method is written in such a way by specifying the params keyword that it accepts string items without specifying the count.

The params keyword is employed in this method signature declarations to denote that a parameter array can be passed to the method. This array can hold zero or more values of a specified type and can also be an optional parameter/hold optional arguments.

The default value for this parameter is an empty array of the type specified in the method signature. For example, when a method containing the argument 'params object[] objects' is called without any parameters, it creates an empty array of objects.

As shown below, "AddToShoppingBasket" can be invoked with a variable number of arguments of string parameters. The params keyword simplifies the syntax for the method call by allowing developers to pass the optional parameters directly without explicitly creating an array.

class Program
{
    AddItemsToShoppingBasket("cake", "pizza", "cold drink");
    AddItemsToShoppingBasket("snacks", "burger");
    AddItemsToShoppingBasket(); // Valid with zero parameters
}
Considerations and Best Practices

Now that we have introduced the params keyword in general let us dive deep into some considerations and best practices of the 'params' keyword.

The parameter type must be a one-dimensional array.

To use the params keyword specified in the method "AddItemsToShoppingBasket" defined above, we can pass a one-dimensional array instead of manually calling the method using parameters like below.

// example

class Program
{
    var items = [] {"cake", "pizza", "cold drink"}; // one-dimensional string array
    AddItemsToShoppingBasket(items); // works
    AddItemsToShoppingBasket("cake", "pizza", "cold drink"); // same as above line

}

Can pass a comma-separated list of arguments for the type of the array elements.

While using a method with the params keyword, we can pass multiple values of arguments as comma-separated values.

// example method signature

class Program
{
    AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // comma separated values
    AddItemsToShoppingBasket("snacks");
}
Pass an array of arguments of the correct type

The below code throws an error if we try to add items of type int into the shopping basket.

// example

AddItemsToShoppingBasket("snacks",2,"burger"); // error
AddItemsToShoppingBasket(2,3,4); // error as params type is string

This occurs as the array argument is a string type and not an int type.

Params should be the last parameter in the Method

No additional parameters are permitted after the params parameter in a method signature declaration, and only one params argument is permitted in a method parameters declaration.

Params should be the last argument of the method signature. This means that all required parameters need to be specified before the params argument.

This is shown in the following code.

static void Main(string[] args)
{
    public static void AddItemsToShoppingBasket(decimal total, params string[] items)
    {
        // ....
    } // This works
}

static void Main(string[] args)
{
    public static void AddItemsToShoppingBasket(decimal total, int totalQuantity, params string[] items)
    {
        // ....
    } // This works
}

static void Main(string[] args)
{
    // Compiler error, This does not work as the params argument is declared before other arguments
    public static void AddItemsToShoppingBasket(params string[] items, decimal total, int totalQuantity)
    {
        // ....
    }
}

Only One params keyword.

There can only be one params parameter in a method signature.

class Program
{
    static void Main(string[] args)
    {
        public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity)
        {
            // Compiler error, This does not work.
        }
    }
}

You can pass no arguments.

If you send no arguments, the length of the params list is zero.

AddItemsToShoppingBasket(); // Works

For any parameter with params, an argument is considered optional and can be called without passing parameters.

Code Example

Here is a complete code example written in C# that shows how to pass different numbers of variables in a params method as a params argument and read these values back in the caller code.

Create a new console application

In Visual Studio, select Create New Project to get the below window. Here, you can provide the Solution Name, Project Name, and paths. Once this information is entered, click next to create the console application ready to start coding.

 Now, add the code below.

class Program
{
    List<string> cart = new List<string>();

    void AddItemsToShoppingBasket(params string[] items)
    {
        for (int i = 0; i < items.Length; i++)
        {
            cart.Add(items[i]);
        }
    }

    // caller code
    static void Main(string[] args)
    {
        Console.WriteLine("Params Example");

        Program program = new Program();

        Console.WriteLine("Enter the cart items as comma separated values");
        var itemsString = Console.ReadLine();

        if (itemsString != null)
        {
            var items = itemsString.Split(",").ToArray();
            program.AddItemsToShoppingBasket(items);
        }

        program.AddItemsToShoppingBasket("Sample1", "Sample2");

        Console.WriteLine("-------------------------------------------------------");
        Console.WriteLine("Display Cart");

        foreach (var item in program.cart)
        {
            Console.WriteLine(item);
        }
    }
}

Output

The output of the above code looks like the following.


 

ASP.NET Core 9.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

Read More...

Thursday, 28 November 2024

IExceptionHandler in.NET Core 8 for Improved Exception Handling

Leave a Comment

Determining how our programs behave requires proper error handling. It involves developing consistent answer formats for our applications so that we can continue to follow a normal process even if something goes wrong. We have a new and improved way to handle problems in our apps thanks to the IExceptionHandler abstraction that comes with.NET 8.

What is an IExceptionHandler?

An interface called IExceptionHandler is used in ASP.NET Core applications to handle exceptions. It outlines an interface that we can use to deal with various exceptions. This enables us to create unique logic that responds to specific exceptions or sets of exceptions according to their type, logging and generating customized error messages and responses.

Why use IExceptionHandler?

We can create more reliable and user-friendly APIs by utilizing IExceptionHandler, which provides a strong and adaptable method for handling exceptions in .NET APIs. In order to handle various exception types, we can also implement IExceptionHandler in standard C# classes. By doing this, we can easily maintain and modularize our applications.

By customizing the responses to the individual exceptions, IExceptionHandler enables us to provide more detailed error messages. This is useful for creating user interfaces that allow us to route users to a specific error page in the event that one of our APIs throws an exception.

Furthermore, because .NET 8 already has the middleware implemented for us through the IExceptionHandler interface, we don't always need to create custom global exception handlers for our applications when using the IExceptionHandler interface.

As an illustration

Let’s create the GlobalExceptionHandler.cs file in our application.

public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
    private readonly ILogger<GlobalExceptionHandler> _logger = logger;
    public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
    {
        _logger.LogError(exception, "An unexpected error occurred");
        string? currentId = Activity.Current?.Id ?? httpContext.TraceIdentifier;
        Dictionary<string, object> otherDetails = new()
        {
            { "CurrentId", currentId },
            { "TraceId", Convert.ToString(Activity.Current!.Context.TraceId)! }
        };
        await httpContext.Response.WriteAsJsonAsync(
            new ProblemDetails
            {
                Status = (int)HttpStatusCode.InternalServerError,
                Type = exception.GetType().Name,
                Title = "An unexpected error occurred",
                Detail = exception.Message,
                Instance = $"{httpContext.Request.Method} {httpContext.Request.Path}",
                Extensions = otherDetails!
            },
            cancellationToken
        );
        return true;
    }
}

Next, let's set up the dependency injection container to register our exception handler.

builder.Services.AddExceptionHandler<GlobalExceptionHandler>();

Our application will automatically call the GlobalExceptionHandler handler whenever an exception occurs. According to RFC 7807 specifications, the API will also produce ProblemDetails standardized responses. We will have more control over how to handle, format, and intercept error responses in this way.

Let's now complete the application request pipeline by adding the middleware:

app.UseExceptionHandler(opt => { });

Let’s run the application and execute the API so we are able to see whether our global exception handler is executing when any exception is raised in our application and showing the details in the API response or not.



Managing various Exception Types

We implement distinct instances of IExceptionHandler, each handling a particular type of exception when handling various error types. Next, by invoking the AddExceptionHandler<THandler>() extension method, we can register each handler in the dependency injection container. It's important to remember that we should register exception handlers in the order in which we want them to be executed.

Let’s create an exception handler to handle The timeout exception handler.

public class TimeoutExceptionHandler(ILogger<TimeoutExceptionHandler> logger) : IExceptionHandler
{
    private readonly ILogger<TimeoutExceptionHandler> _logger = logger;

    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken)
    {
        _logger.LogError(exception, "A timeout occurred");
        if (exception is not TimeoutException)
        {
            return false;
        }
        httpContext.Response.StatusCode = (int)HttpStatusCode.RequestTimeout;
        string? currentId = Activity.Current?.Id ?? httpContext.TraceIdentifier;
        Dictionary<string, object> otherDetails = new()
        {
            { "CurrentId", currentId },
            { "TraceId", Convert.ToString(Activity.Current!.Context.TraceId)! }
        };
        await httpContext.Response.WriteAsJsonAsync(
            new ProblemDetails
            {
                Status = (int)HttpStatusCode.RequestTimeout,
                Type = exception.GetType().Name,
                Title = "A timeout occurred",
                Detail = exception.Message,
                Instance = $"{httpContext.Request.Method} {httpContext.Request.Path}",
                Extensions = otherDetails
            },
            cancellationToken);
        return true;
    }
}

Let’s register the services in the dependency injection.

builder.Services.AddExceptionHandler<TimeoutExceptionHandler>();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
 

We learned the new technique and evolved together.

Happy coding!

ASP.NET Core 9.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...

Wednesday, 27 November 2024

Best and Cheap Drupal 11.0.4 Hosting in the UK

Leave a Comment
To choose Drupal 11.0.4 Hosting in the UK for your site, we recommend the following Best & Cheap Drupal 11.0.4 Hosting companies, which have been proven reputable and trustworthy by our editors. Drupal 11.0.4 is a free software package that enables individuals or communities of users to effortlessly publish, manage, and organize a wide range of material on a website. The Ajax system now checks URLs before sending an Ajax request. Existing code that uses the Drupal Ajax API in any of the typical methods should continue to function following this update. If you have strange Ajax code that does not work with Drupal 11.0.4, you can manually validate the URL using one of two methods.


Drupal shines as a CMS. It provides a user interface that allows you to create and publish your content easily. The platform accommodates unlimited content types, including text and media content, with highly customizable forms. It dynamically retrieves, filters, and presents this content with powerful, yet simple-to-use tools. There are also intuitive content creation tools and powerful in-place editing tools. Drupal controls access to content and features with its sophisticated user role classification and permissions system.

All of the administrative and end-user-facing functionality in Drupal, from fundamental features, such as the ability to log in or create content to dynamic photo galleries and complex voting systems, comes from modules. What you download from Drupal.org is what is referred to as "Drupal core" and it comes packed with all of the most commonly used modules to build a site, but there is a huge variety of contributed modules, which thousands of developers make available for free on Drupal.org.
Drupal is also a powerful website development platform. Drupal adheres to modern object-oriented programming patterns, PHP best practices, HTML5 and YAML standards. It also incorporates other great web technologies, including CKEditor, Symfony2, Twig, jQuery, Backbone.js, and Guzzle. Extending functionality and gaining complete control over the design is accomplished through a robust assortment of add-ons in the form of modules and themes.

Best & Cheap Drupal 11.0.4 Hosting in UK?

https://ukwindowshostasp.net/UK-Drupal-Web-hosting
UKWindowsHostASP.NET revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Some other hosting providers manually execute configuration requests, which can take days. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to UKWindowsHostASP.NET's customers.

UKWindowsHostASP.NET is the best UK Windows Hosting provider that offers the most affordable world class windows hosting solutions for their customers. They provide shared, reseller, cloud, and dedicated web hosting. They currently operate servers in four prestiguous cities in Europe, namely: London (UK), Amsterdam (Netherlands), Frankfurt (Germany), Washington DC (US), Paris (France), Singapore and Chennai (India). Their target is to provide a versatile and dependable one-stop online hosting and marketing shop for the small business entrepreneur, and eliminate the need for you to deal with a host of different online vendors. They offer high quality web hosting, dedicated servers, web design, domain name registration, and online marketing to help lead your business to online success.
https://ukwindowshostasp.net/UK-Drupal-Web-hosting

Leveraging a strong market position within the domain name registration industry, UKWindowsHostASP.NET has carefully nurtured relationships with its customer base and built a feature-rich line of value-added services around its core domain name product offering. By bundling services and providing one-stop shopping, UKWindowsHostASP.NET has successfully grown and enjoyed increased breadth and loyalty of its customer base

Why You Choose UKWindowsHostASP.NET for Drupal 11.0.4

Hosting in UK?

  • 24/7-based Support -They never fall asleep and they run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, they are always behind their desk serving their customers.
  • Excellent Uptime Rate - Their key strength in delivering the service to you is to maintain their server uptime rate. They never ever happy to see your site goes down and they truly understand that it will hurt your onlines business.
  • High Performance and Reliable Server - They never ever overload their server with tons of clients. They always load balance their server to make sure they can deliver an excellent service, coupling with the high performance and reliable server.
  • Experts in Web Hosting - Given the scale of their environment, they have recruited and developed some of the best talent in the hosting technology that you are using.
  • Daily Backup Service - They realise that your website is very important to your business and hence, they never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive.
  • Easy Site Administration - With their powerful control panel, you can always administer most of your site features easily without even needing to contact for their Support Team.
Read More...

Monday, 18 November 2024

ASP.NET Hosting Tutorial: Understanding Param Collection in C# 13

Leave a Comment

The params keyword in C# lets developers pass any number of arguments to a method, making it easier to work with lists or arrays. It was first introduced in C# 1.0 and is still useful today. This blog will dive into the new feature in C# 13 related to params usage


Prerequisites

  • Visual Studio 2022 – 17.12 version
  • .NET 9.0

You can download the Visual Studio Community edition from here.

What is param collection?

The params keyword in C# lets a method take a flexible number of arguments as a single parameter, usually as an array. When a parameter is marked with params, the caller can pass either individual values or an array. This makes it easier to call the method, especially when dealing with optional or unknown numbers of values.

For instance

void PrintParamsWithArray(params int[] numbers)
{
    foreach (var number in numbers)
    {
        Console.WriteLine(number);
    }
}
//The usage would be:
PrintParamsWithArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

Before C# 13, the params keyword could only be used with arrays. However, with this new feature, you can now use params with any collection type.

The recognized collection types are given below.

System.Span<T>, System.ReadOnlySpan<T>, and types that implement System.Collections.Generic.IEnumerable<T> and have an Add method. You can also use interfaces like System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IList<T>, not just specific types.

Let us look at an example.

Use List with params.

internal static class WithList
{
    public static void Display(params List<int> numbers)
    {
        foreach (var number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}
// Usage
Console.WriteLine("Params with List");
WithList.Display([1, 2, 3, 4, 5, 6, 7]);

Use Span with params.

public static void Display(params ReadOnlySpan<int> numbers)
{
    foreach (var number in numbers)
    {
        Console.WriteLine(number);
    }
}
// Usage:
Console.WriteLine("Params with Span");
WithSpan.Display(1, 2, 3, 4, 5);

Let’s run the program, and you’ll see the following output.

The params keyword in C# is a useful tool for managing variable numbers of arguments. Since it was introduced in C# 1.0, it has helped developers write cleaner and more flexible code by making it easier to pass multiple parameters to methods.

Happy Coding!

Best ASP.NET Core 8.0.8 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...

Wednesday, 13 November 2024

ASP.NET Hosting Tutorial: Understanding Keyed Services in .NET 8

Leave a Comment

Dependency injection plays a crucial role in every programming language. Microsoft has introduced many new features and significant enhancements in .Net 8. “Keyed Services” is one of the important, powerful enhancements in the dependency injection shipped with .Net Core 8.

In this article, we will explore Keyed Services .Net 8, illustrating with an example. This article is suitable for beginners, intermediate learners, and professionals.

We are going to cover the following in this article.

  1. How do you deal with multiple implementations of the interface prior to Keyed Services?
  2. Introduction of Keyed Services?
  3. Lifetime scope for Keyed Services.
    • AddKeyedSingleton
    • AddKeyedScoped
    • AddKeyedTransient
  4. How to register and resolve dependencies using Keyed Services

Prerequisites

Below are the prerequisites for Keyed Services.

  1. .NET 8 SDK (RC1 or later version)
  2. Visual Studio 2022 version 17.8 or later

Let’s start with the use case of the Keyed Services.

How do you deal with multiple implementations of the interface prior to Keyed Services?

Let’s assume that we want to implement report generator functionality, which can generate reports on XML, CSV, and PDF as per the user's preference.

Now, think how you will implement this prior to .NET 8. Let’s create a demo MVC core project in .NET Core 6.0.

Step 1. Create a .NET Core MVC project using .NET Core 6.0.

Step 2. Create an Interface called “IReportGenerator”.

namespace WebApplication1.Interfaces
{
    public interface IReportGenerator
    {
        string GenerateReport();
    }
}

Step 3. Create Three classes “CSVReportGenerator”, “XmlReportGenerator”, and “And PDFReportGenerator” and implement the “IReportGenerator” interface.

CSVReportGenerator.cs

public class CSVReportGenerator : IReportGenerator
{
    public string GenerateReport()
    {
        // Actual code of CSV report generator
        return "CSV report";
    }
}

XmlReportGenerator.cs

public class XmlReportGenerator: IReportGenerator
{
   public string GenerateReport()
   {
     //actual code of xml report generator
      return "XML Report";
   }
}

PDFReportGenerator.cs

public class PDFReportGenerator: IReportGenerator
{
   public string GenerateReport()
   {
      //actual code of xml report gen
      return "PDF Report";
   }
}

Step 4. Register dependencies in the program.cs file.

builder.Services.AddSingleton<IReportGenerator, XmlReportGenerator>();
builder.Services.AddSingleton<IReportGenerator, PDFReportGenerator>();
builder.Services.AddSingleton<IReportGenerator, CSVReportGenerator>();

We have registered all three classes in the program.cs file.

Step 5. Make the code changes in the HomeController.

public class HomeController: Controller
{
   private readonly ILogger<HomeController> _logger;
   private readonly IReportGenerator _reportGenerator;
   public HomeController (ILogger<HomeController> logger, IReportGenerator reportGenerator)
   {
      _logger logger;
      _reportGenerator = reportGenerator;
   }
   public IActionResult Index()
   {
       ViewBag.ReportGenerator=_reportGenerator.GenerateReport();
       return View();
   }
}

In the above code, we have injected “IReportGenerator” as a parameter in the controller constructor, which is then called the GenerateReport method in the index action method.

Step 6. Make code changes in the Index.cshtml file.

In the code below, we are printing the GeneratorReport output in the welcome message.

@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome from @ViewBag.ReportGenerator</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

Step 7. Run the application and observe the output.

Output

We observed that only the last registered service was retrieved. In this case, the CSV report is the last registered service.

Now, the next question is how to get another registered service, if required, like XML Report or PDF Report. We can make the code changes below in the HomeController and achieve it.

public class HomeController: Controller
{
  private readonly ILogger<HomeController> _logger;
  private readonly IEnumerable<IReportGenerator> _reportGenerator;
  public HomeController (ILogger<HomeController> logger, IEnumerable<IReportGenerator> reportGenerator)
  {
    _logger logger;
    _reportGenerator = reportGenerator;
  }
  public IActionResult Index()
  {
     ViewBag.ReportGenerator=_reportGenerator.ElementAt(0).GenerateReport();
     return View();
  }
}

Execute the program and see the output. This time, we will get the XmlReport.

Introduction of Keyed Services

Keyed Services allows us to register and retrieve dependency injection using Key.

You can register and retrieve multiple implementations of the same interface using a key.

Lifetime scope for Keyed Services

Microsoft introduced three new extension methods for the Lifetime scope of keyed services.

  1. AddKeyedSingleton
  2. AddKeyedScoped
  3. AddKeyedTransient

These extension methods are like AddSinglton, AddScoped, and AddTransient methods in .Net core, except it allow us to use “key” to define lifetime scope of dependencies.

How to register and resolve dependencies using Keyed Services?

Let’s create the same report example using .Net 8 Keyed Service.

Step 1. Create a .Net Core MVC project using .Net Core 8.0

Step 2. Create interface “IReportGenerator” and three classes “CSVReportGenerator”, “PDFReportGenerator”, and “XMLReportGenerator” in the previous section of Step 2 and Step 3.

Step 3. Register dependencies in the Program.cs file like below.

builder.Services.AddKeyedSingleton<IReportGenerator, XmlReportGenerator>("XML");
builder.Services.AddKeyedSingleton<IReportGenerator, PDFReportGenerator>("PDF");
builder.Services.AddKeyedSingleton<IReportGenerator, CSVReportGenerator>("CSV");

we have used “AddKeyedSingleton” to register dependencies.

Step 4. Make the below code changes in HomeController.

public class HomeController: Controller
{
  private readonly ILogger<HomeController> _logger;
  private readonly IReportGenerator _xmlreportGenerator;
  private readonly IReportGenerator _pdfreportGenerator;

  public HomeController (ILogger<HomeController> logger, [FromKeyedServices ("XML")] IReport
  Generator xmlReportGenerator, [FromKeyedServices ("PDF")] IReportGenerator pdfReportGenerator)
  {
    _logger logger;
    _xmlreportGenerator = xmlReportGenerator;
    _pdfreportGenerator = pdfReportGenerator;
  }
  public IActionResult Index()
  {
    ViewBag.ReportGenerator = _xmlreportGenerator.GenerateReport() + "Second Report +
    _pdfreportGenerator.GenerateReport();
    return View();
  }
}

In this code, we have used [FromKeyedServices] to retrieve dependencies based on the Key.

Step 5. Copy index.cshtml code from the previous example, step 6.

Step 6. Execute the program and see the output.

Output

I hope you enjoyed this article and learned something new.

Best ASP.NET Core 8.0.8 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...