aspnet

Understanding Dependency Injection in .NET Core

Learn what Dependency Injection and IoC are and what .NET Core provides you to support them.

Dependency Injection is one of the most known techniques that help you to create more maintainable code. .NET Core provides you with extensive support to Dependency Injection, but it may not always be clear how to apply it. This tutorial will try to clarify the various Dependency Injection concepts and will introduce you to the support provided by .NET Core.

The Dependency Problem

Have you ever had to change a lot of code because of a new simple requirement? Have you ever had a hard time trying to refactor part of an application? Have you ever been in trouble writing unit tests because of components that required other components?

If you answered yes to any of these questions, maybe your codebase suffers from dependency. It’s a typical disease of the code of an application when its components are too coupled. In other words, when a component depends on another one in a too-tight way. The main effect of component dependency is the maintenance difficulty of the code, which, of course, implies a higher cost.

A dependency example

Take a look at a typical example of code affected by dependency. Start by analyzing these C# classes:

using System;
using System.Collections.Generic;

namespace OrderManagement
{
    public class Order
    {
        public string CustomerId { get; set; }
        public DateTime Date { get; set; }
        public decimal TotalAmount { get; set; }
        public List<OrderItem> Items { get; set; }

        public Order()
        {
            Items = new List<OrderItem>();
        }
    }

    public class OrderItem
    {
        public string ItemId { get; set; }
        public decimal Quantity { get; set; }
        public decimal Price { get; set; }
    } 
}

This code defines two classes, Order and OrderItem, that represent the order of a customer. The orders are managed by the OrderManager class implemented as follows:

using System.Threading.Tasks;

namespace OrderManagement
{
    public class OrderManager
    {
        public async Task<string> Transmit(Order order)
        {
            var orderSender = new OrderSender();

            return await orderSender.Send(order);
        }
    }
}

The OrderManager class implements the Transmit() method, which sends the order to another service to process. It relies on the OrderSender class to actually send the order received as an argument.

This is the code implementing the OrderSender class:

using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace OrderManagement
{
    public class OrderSender
    {
        private static readonly HttpClient httpClient = new HttpClient();

        public async Task<string> Send(Order order)
        {
            var jsonOrder = JsonSerializer.Serialize<Order>(order);
            var stringContent = new StringContent(jsonOrder, UnicodeEncoding.UTF8, "application/json");

            //This statement calls a not existing URL. This is just an example...
            var response = await httpClient.PostAsync("https://mymicroservice/myendpoint", stringContent);

            return response.Content.ReadAsStringAsync().Result;

        }
    }
}

As you can see, the Send() method of this class serializes the order and send it via HTTP POST to a hypothetical microservice that will process it.

The code shown here is not meant to be realistic. It is just a rough example.

What happens if you need to change the way of sending an order? For example, suppose you also want to send orders via e-mail or to send them to another microservice that uses gRPC instead of HTTP. Also, how comfortable do you feel to create a unit test for the OrderManager class?

Since OrderManager depends on OrderSender, you will be forced to change in some way both classes to support multiple sender types. Changes in the lower-level component (OrderSender) may affect the higher-level component (OrderManager). Even worse, it will be almost impossible to automatically test the OrderManager class without risking to mess your code.

This is just a simple study case. Think of the impact that dependency may have in a more complex scenario with many dependent components. That could really become a huge mess.

The Dependency Inversion Principle

The last of the SOLID principles proposes a way to mitigate the dependency problem and make it more manageable. This principle is known as the Dependency Inversion Principle and states that:

  • High-level modules should not depend on low-level modules. Both should depend on abstractions
  • Abstractions should not depend on details. Details should depend on abstractions.

You can translate the two formal recommendations as follows: in the typical layered architecture of an application, a high-level component should not directly depend on a lower-level component. You should create an abstraction (for example, an interface) and make both components depend on this abstraction.

Translated in a graphical way, it appears as shown by the following picture:

Dependency Inversion Principle Diagram

Of course, all of this may seem too abstract. Well, this article will provide you with examples to clarify the concepts about dependency and the techniques to mitigate it. While the general concepts are valid for any programming language and framework, this article will focus on the .NET Core framework and will illustrate the infrastructure it provides you to help in reducing component dependency.

A trip in the dependency lingo

Before exploring what .NET provides you to fight the dependency disease of your code, it’s necessary to put some order in the terminology. You may have heard many terms and concepts about code dependency, and some of them seem to be very similar and may have been confusing. Well, here is an attempt to give a proper definition of the most common ones:

  • Dependency Inversion Principle: it’s a software design principle; it suggests a solution to the dependency problem but does not say how to implement it or which technique to use.
  • Inversion of Control (IoC): this is a way to apply the Dependency Inversion Principle. Inversion of Control is the actual mechanism that allows your higher-level components to depend on abstraction rather than the concrete implementation of lower-level components.Inversion of Control is also known as the Hollywood Principle. This name comes from the Hollywood cinema industry, where, after an audition for an actor role, usually the director says, don’t call us, we’ll call you.
  • Dependency Injection: this is a design pattern to implement Inversion of Control. It allows you to inject the concrete implementation of a low-level component into a high-level component.
  • IoC Container: also known as Dependency Injection (DI) Container, it is a programming framework that provides you with an automatic Dependency Injection of your components.

Dependency Injection approaches

Dependency Injection is maybe the most known technique to solve the dependency problem.

You can use other design patterns, such as the Factory or Publisher/Subscriber patterns, to reduce the dependency between components. However, it mostly derives on the type of problem your code is trying to solve.

As said above, it is a technique to providing a component with its dependencies, preventing the component itself from instantiating by themselves. You can implement Dependency Injection on your own by creating instances of the lower-level components and passing them to the higher-level ones. You can do it using three common approaches:

  • Constructor Injection: with this approach, you create an instance of your dependency and pass it as an argument to the constructor of the dependent class.
  • Method Injection: in this case, you create an instance of your dependency and pass it to a specific method of the dependent class.
  • Property Injection: this approach allows you to assign the instance of your dependency to a specific property of the dependent class.

.NET Core and the Dependency Injection

You can implement Dependency Injection manually by using one or more of the three approaches discussed before. However, .NET Core comes with a built-in IoC Container that simplifies Dependency Injection management.

The IoC Container is responsible for supporting automatic Dependency Injection. Its basic features include:

  • Registration: the IoC Container needs to know which type of object to create for a specific dependency; so, it provides a way to map a type to a class so that it can create the correct dependency instance.
  • Resolution: this feature allows the IoC Container to resolve a dependency by creating an object and injecting it into the requesting class. Thanks to this feature, you don’t have to instantiate objects manually to manage dependencies.
  • Disposition: the IoC Container manages the lifetime of the dependencies following specific criteria.

You will see these features in action in a while. But before this, some basic information is needed.

The .NET Core built-in IoC Container implements the IServiceProvider interface. So if for some reason, you want to create your own IoC Container, you should implement this interface. In .NET Core, the dependencies managed by the container are called services. You have two types of services:

  • Framework services: these services are part of the .NET Core framework; some examples of framework services are IApplicationBuilderIConfigurationILoggerFactory, etc.
  • Application services: these are the services that you create in your application; since the IoC doesn’t know them, you need to register them explicitly.

Dealing with Framework Services

As a .NET Core developer, you’ve already used the built-in IoC Container to inject framework services. Indeed, .NET Core heavily relies on it. For example, the Startup class in an ASP.NET application uses Dependency Injection extensively:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
            // ... code ...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
            // ... code ...
    }

        // ... code ...
}

In this example, the Startup() constructor requires a configuration parameter implementing the IConfiguration type. Since IConfiguration is one of the framework service types, the IoC Container knows how to create an instance of it and inject it into the Startup class applying the Constructor Injection approach. The same applies to the Configure() method. Keep in mind, however, that only the following framework service types can be injected in the Startup() constructor and in the Configure() method of a standard ASP.NET application: IWebHostEnvironmentIHostEnvironment, and IConfiguration. This is a special case for framework services because you don’t need to register them.

Registering framework services

In general, you have to register services needed by your ASP.NET application in the ConfigureServices() method of the Startup class. This method has an IServiceCollection parameter representing the list of services your application depends on. Practically, the collection represented by this parameter allows you to register a service in the IoC Container. Consider the following example:

public class Startup
{
         // ... code ...
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            });
    }

        // ... code ...
}

Here, you are registering a dependency for managing authentication for your application. In this specific case, you are using the extension methodAddAuthentication() with the parameters describing the authentication type you want to use. The framework provides extension methods to register and configure dependencies for the most common services. It also provides the Add() method to register generic dependencies, as in the following example:

public class Startup
{
         // ... code ...
    public void ConfigureServices(IServiceCollection services)
    {
        services.Add(new ServiceDescriptor(typeof(ILog), new MyLogger()));  
    }

        // ... code ...
}

In this case, you are registering a log service implementing the ILog interface. The second parameter of the Add() method is an instance of the MyLogger class you have implemented in your project. As you may guess, this registration creates a singleton service, i.e., a single instance of the MyLogger class that will fulfill any requests coming from your application.

Service lifetimes

This single instance of your dependency will live for the entire lifetime of your application. This may be suitable for a service like a logger, but it is unacceptable for other services. The IoC Container allows you to control the lifetime of a registered service. When you register a service specifying a lifetime, the container will automatically dispose of it accordingly. You have three service lifetimes:

  • Singleton: this lifetime creates one instance of the service. The service instance may be created at the registration time by using the Add() method, as you saw in the example above. Alternatively, the service instance can be created the first time it is requested by using the AddSingleton() method.
  • Transient: by using this lifetime, your service will be created each time it will be requested. This means, for example, that a service injected in the constructor of a class will last as long as that class instance exists. To create a service with the transient lifetime, you have to use the AddTransient() method.
  • Scoped: the scoped lifetime allows you to create an instance of a service for each client request. This is particularly useful in the ASP.NET context since it allows you to share the same service instance for the duration of an HTTP request processing. To enable the scoped lifetime, you need to use the AddScoped() method.

Choosing the right lifetime for the service you want to use is crucial both for the correct behavior of your application and for better resource management.

Managing Application Services

Most of the concepts you learned from framework services are still valid for your application services. However, framework services are already designed to be injectable. The classes you define in your application need to be adapted to leverage Dependency Injection and integrate with the IoC Container.

To see how to apply the Dependency Injection technique, recall the order management example shown early in this article and assume that those classes are within an ASP.NET application. You can download the code of that application from this GitHub repository by typing the following command in a terminal window:

git clone -b starting-point --single-branch https://github.com/sniper57/dependency-injection-dotnet-core

This command will clone in your machine just the branch starting-point of the repository. After cloning the repository, you will find the dependency-injection-dotnet-core folder on your machine. In this folder, you have the OrderManagementWeb subfolder containing the ASP.NET Core project with the classes shown at the beginning of this article. In this section, you are going to modify this project to take advantage of the Dependency Injection and the built-in IoC Container.

Defining the abstractions

As the Dependency Inversion Principle suggests, modules should depend on abstractions. So, to define those abstractions, you can rely on interfaces.

Add a subfolder to the OrderManagementWeb folder and call it Interfaces. In the Interfaces folder, add the IOrderSender.cs file with the following content:

// OrderManagementWeb/Interfaces/IOrderSender.cs

using System.Threading.Tasks;
using OrderManagement.Models;

namespace OrderManagement.Interfaces
{
    public interface IOrderSender
    {
        Task<string> Send(Order order);
    }
}

This code defines the IOrderSender interface with just one method, Send(). Also, in the same folder, add the IOrderManager.cs file with the following interface definition:

// OrderManagementWeb/Interfaces/IOrderManager.cs

using System.Threading.Tasks;
using OrderManagement.Models;

namespace OrderManagement.Interfaces
{
    public interface IOrderManager
    {
        public Task<string> Transmit(Order order);
    }
}

The above code defines the IOrderManager interface with the Transmit() method.

Depending on the abstractions

Once defined the abstractions, you have to make your classes depending on them instead of the concrete class instances. As a first step, you need to redefine the OrderSender class so that it implements the IOrderSender interface. You also rename the class into HttpOrderSender to point out that this implementation sends the order via HTTP. So, open the OrderSender.cs file in the Managers folder and replace its content with the following:

// OrderManagementWeb/Managers/OrderSender.cs

using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using OrderManagement.Interfaces;
using OrderManagement.Models;

namespace OrderManagement
{
    public class HttpOrderSender : IOrderSender
    {
        private static readonly HttpClient httpClient = new HttpClient();

        public async Task<string> Send(Order order)
        {
            var jsonOrder = JsonSerializer.Serialize<Order>(order);
            var stringContent = new StringContent(jsonOrder, UnicodeEncoding.UTF8, "application/json");

            //This statement calls a not existing URL. This is just an example...
            var response = await httpClient.PostAsync("https://mymicroservice.lan/myendpoint", stringContent);

            return response.Content.ReadAsStringAsync().Result;

        }
    }
}

Now, you need to redefine also the OrderManager class so that it implements the IOrderManager interface. Open the OrderManager.cs file in the Managers folder and replace its content with the following:

// OrderManagementWeb/Managers/OrderManager.cs

using System.Threading.Tasks;
using OrderManagement.Interfaces;
using OrderManagement.Models;

namespace OrderManagement
{
    public class OrderManager : IOrderManager
    {
        private IOrderSender orderSender;

        public OrderManager(IOrderSender sender)
        {
            orderSender = sender;
        }

        public async Task<string> Transmit(Order order)
        {
            return await orderSender.Send(order);
        }
    }
}

You may notice that, differently from the previous version of the class, the Transmit() method no longer creates an instance of the OrderSender class. The dependency is now accessed via the class constructor.

With these changes, you broke the dependency between the OrderManager and the HttpOrderSender classes. Now, the OrderManager depends on the IOrderSender interface, i.e., its abstraction.

Registering the dependencies

Now you need to tell the IoC Container how to manage the dependencies based on the abstraction you have defined. In other words, you need to register the dependencies. As said, this registration happens in the Startup class of the project. So, open the Startup.cs file and replace the ConfigureServices() method with the following:

// OrderManagementWeb/Startup.cs

public class Startup
{
    // ...code ...

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddScoped<Interfaces.IOrderSender, HttpOrderSender>();
            services.AddScoped<Interfaces.IOrderManager, OrderManager>();
        }

    // ...code ...

}

As you can see, you registered the dependencies by using the generic version of the AddScoped() method. Here you are asking the IoC Container to create an instance of the HttpOrderSender class whenever a request for the IOrderSender type is detected. Similarly, it should create an instance of the OrderManager class when theIOrderManager type is requested.

Note that even the AddController() method is an extension method provided by Microsoft.Extensions.DependencyInjection library that registers services for the Web API controllers.

Injecting the dependencies

Now it’s time to actually use all these dependencies. So, open the OrderController.cs file in the Controllers folder and replace its content with the following code:

// OrderManagementWeb/Controllers/OrderController.cs

using Microsoft.AspNetCore.Mvc;
using OrderManagement.Interfaces;
using OrderManagement.Models;

namespace OrderManagement.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        private IOrderManager orderManager;

        public OrderController(IOrderManager orderMngr)
        {
            orderManager = orderMngr;
        }

        [HttpPost]
        public ActionResult<string> Post(Order order)
        {
            return Ok(orderManager.Transmit(order));
        }
    }
}

The new version of the Web API controller defines a private orderManager variable. Its value represents the instance of a service implementing the IOrderManager interface. The value of this variable is assigned in the constructor, which has an IOrderManager type parameter. With this parameter, the constructor is requesting the IoC Container a service instance of that type. The IoC Container searches in its service collection a registration that can satisfy this request and passes such an instance to the controller. But that’s not all. The IoC Controller also looks for other indirect dependencies and resolve them. This means that while creating the instance of the OrderManager class, the IoC Container also resolves its internal dependency on the IOrderSender abstraction. So you don’t have to worry about indirect dependencies: they are all resolved under the hood simply because the Web API controller declared to need a registered service.

As you noticed in these examples, the Constructor Injection is the default approach used by the IoC Container to inject dependencies in a class. If you want to use the Method Injection approach, you should request it explicitly by using the FromServices attribute. This example shows how you could use this attribute:

[HttpPost]
public ActionResult<string> Post([FromServices]IOrderManager orderManager)
{
    return Ok(orderManager.Transmit(order));
}

The third injection approach, the Property Injection, is not supported by the built-in IoC Container.

Dependency Injection in a Console Application

In the previous section, you implemented Dependency Injection for an ASP.NET Web application. You followed a few steps to register and get your dependencies automatically resolved by the built-in IoC Container. However, you may still feel something magic in the way it happens since the ASP.NET Core infrastructure provides you with some implicit behaviors. However, the Dependency Injection mechanism provided by the IoC Container is not just for Web applications. You can use it in any type of application.

In this section, you will learn how to leverage the IoC infrastructure in a console application, and some behaviors that may still look obscure will be hopefully clarified. So, move in the dependency-injection-dotnet-core folder you created when cloned the ASP.NET application and run the following command in a terminal window:

dotnet new console -o OrderManagementConsole

This command creates an OrderManagementConsole folder with a basic console application project. Now, copy in the OrderManagementConsole folder the InterfacesManagers, and Models folders from the ASP.NET project you modified in the previous section. Basically, you are reusing the same classes related to the order management process you defined in the ASP.NET project.

After this preparation, the first step to enable your console application to take advantage of the IoC Container is to add the Microsoft.Extensions.DependencyInjection package to your project with the following command:

dotnet add package Microsoft.Extensions.DependencyInjection

Then, you have to write some code to set up the IoC Container in your console application. Open the Program.cs file and replace its content with the following:

// OrderManagementConsole/Program.cs

using System;
using Microsoft.Extensions.DependencyInjection;
using OrderManagement;
using OrderManagement.Interfaces;
using OrderManagement.Models;

namespace OrderManagementConsole
{
    class Program
    {
        private static IServiceProvider serviceProvider;

        static void Main(string[] args)
        {
            ConfigureServices();

            var orderManager = serviceProvider.GetService<IOrderManager>();
            var order = CreateOrder();

            orderManager.Transmit(order);
        }

        private static void ConfigureServices()
        {
            var services = new ServiceCollection();

            services.AddTransient<IOrderSender, HttpOrderSender>();
            services.AddTransient<IOrderManager, OrderManager>();

            serviceProvider = services.BuildServiceProvider();
        }

        private static Order CreateOrder()
        {
            return new Order {
                CustomerId = "12345",
                Date = new DateTime(),
                TotalAmount = 145,
                Items = new System.Collections.Generic.List<OrderItem>
                {
                    new OrderItem {
                        ItemId = "99999",
                        Quantity = 1,
                        Price = 145
                    }
                }
            };
        }
    }
}

You see that the first operation in the Main() method of the Program class is configuring the services. Taking a look at the ConfigureServices() method, you see that this time you have to create the services collection explicitly. Then, you register your services with the transient lifetime: the dependencies should live just the time needed to manage the order. Finally, you get the service provider by using the BuildServiceProvider() method of the services collection and assign it to the serviceProvider private variable.

You use this service provider to get an instance of a registered service. For example, in the Main() method, you get an instance of the IOrderManager service type by using the GetService<IOrderManager>() method. From now on, you can use this instance to manage an order. Of course, as in the ASP.NET case, the orderManager instance has any indirect dependency resolved.

Finally, the CreateOrder() method just creates a dummy order to be passed to the Transmit() method of the order manager.

Summary

This article tried to clarify some concepts related to the Dependency Injection design pattern and focused on the infrastructure provided by .NET Core to support it. After introducing a few general definitions, you learned how to configure an ASP.NET Core application to use the built-in IoC container and register framework services. Then, you adapted the classes of an ASP.NET application to apply the Dependency Inversion Principle and discovered how to register your dependency in the IoC Container specifying the desired lifetime. Finally, you saw how to use the IoC Container even in a console application.

You can find the full source code discussed in this article in this GitHub repository.

Difference between GET and POST Method

Http protocol supports the following methods to retrieve data such as get, post, put, delete etc. In this article, I will tell you about the difference between GET and POST methods.

These methods are basically used to get and send any data. Because of these methods, the request-response between server and client exist. To send data streams we use these two methods. GET and POST are the most common HTTP methods.

Difference between GET and POST Method

GETPOST
We add parameters in URL and get data in response.Send additional data from the client or browser to the server.
Sends data as part of URI (uniform resource identifier)Sends data as HTTP content.
get return same results every time.The post method implements in that way it changes with every request.
We can send limited data in the header. We can send a large amount of data because its part of the request body.
It is not much secure because data is exposed to URL and we can easily bookmark it and send it. It  is more secure because data is passed in the request body and user not able to bookmark it
You can cache the data.You cannot cache post request data.
GET is bounded by the max. URL length continued by the browser and web server.POST doesn’t have such conditions.
GET is used to request data from a particular resource.POST is used to send info to a server to create/update a resource.
parameters passed  in URLparameters passed in body
This is not happening in get method.Use POST for destructive things such as creation, editing, and deletion.
get is used for fetching documents.post used for updating data.
in get we pass things like customer id, uId to get a response.post request sends information to server like customer info, file upload etc.

Check out the example of both requests.

GET Request:

GET https://api.github.com/users/{name}

Here you can pass name according to that you will get data.

GET https://api.github.com/users/sniper57

POST Request:

In this you will have to send content-type such as multipart/form-data, application/json,  application/x-www-form-urlencoded and object or data that you have to pass in body.

Host: foobar.example

Content-Type: application/json

Object- [{name1:value1},{name2:value2}]

In this you are posting JSON data to API.

Comment down below if you have any queries related to get vs post methods.

5 Facile Yet Incredibly Valuable Ways to Enhance ASP.NET Developer’s Efficiency

The ASP.Net Development has arguably redefined and restructured the ambit of web application development. The new age capabilities of the platform created by Microsoft has features abound of developers to let them think out of the box and create something that paves way for innovation. Creating exclusive application become a prospect rather too realistic and as more number of developers and development companies lean towards ASP.NET, we are sure to witness better and faster web apps.

The framework is also continuously changing and it is being made sure that there are regular upgrades. For an enterprise providing the ASP.NET development services to a client – locally or offshore – it is imperative to keep glued to those changes and let them not surprise them and the clients. To upgrade themselves to the changes, developers need to rise up to the occasion and raise their skill levels and optimize the way they work. There are ways to do so, and those ways are met with certain challenges as well. But they also produce favorable results for businesses. So, here is how you can proceed to hone your results as a developer:

Also Read: http://blogs.magistechnologiesinc.com/5-things-you-must-consider-before-using-asp-net-development/(opens in a new tab)

Make Handling the Requests an Asynchronous Exercise

The customary practice in ASP.Net Development is managing the incoming request synchronously. While this kind of process has its set of benefits, you cannot set priorities with this practice, which leads to mismanagement of time. As the requests are placed in a queue, there is a method to how they are handled. So far, so good, but the lack of prioritization only works the other way for you – the wrong way that is. By using asynchronous pages, you can reduce the total request handling time and let more important applications to run first. 

Use the Browser’s Tools and Extensions

The browsers like Google Chrome and Mozilla Firefox comes with their own set of tools to help developers spend less time in writing darn-out codes and plug their applications with incredible features. The oversight leaded to ignoring these tools will only lead to increased time in developing apps and probably lesser efficiency as well. Look for the tools that are relevant to the app and leverage them in the best way you can. 

Pool the connections to Free up Some Resources

The way applications are connected to the database eats up a lot of resources, which can otherwise be saved by the more optimized practice of connecting pooling. It also helps the TCP connections, though keeping an eye towards
discrepancies like connection leaks becomes more imperative. 

Do not Keep Debuggers Running at All Times

While ASP.NET works in a great way to make sure the errors do not creep in and go unnoticed through the use of various debuggers and tracers to let you know, they also have an impact over the application development speed metrics. If you keep them on, the debuggers will render the whole process slow and bring a marked difference in the way applications are being executed. This further impacts the performance – a not too desirable prospect by any stretch. As and when you need it, you can switch on the debuggers to locate and correct the errors to make sure they don’t surface at run-time. 

Make the Most of Cache Class

Developers, both beginners and experts, often undermine the importance of the cache class. In fact, they ignore the benefits that the overall caching mechanism can provide them with. This mechanism is highly important for making a backup of resources while classifying their validity. The cache class makes this process be carried out with ease. As and when an object is not allowed to cache, the callbacks are summoned. With a nod to the growing evolvement of ASP.NET, developers feel the heat to stay abreast to the latest and most resourceful practices. And if they happen to be a part of a large scale ASP.NET development company, there is an escalated urgency.

5 Things You Must Consider Before Using ASP.NET Development

Today’s contemporary web needs expect you to opt for a programming framework that comes loaded with remarkable benefits. Before choosing a particular framework, you must gauge it in terms of ease-of-use and scalability. Amongst the wide range of programming frameworks available in the web market, ASP.NET has been successful in making it to the list of leading web development frameworks used by web developers across the globe. If you too are about to leverage ASP.NET features for building remarkable web solutions then this is a post you can’t afford to miss. Here, I’ve covered five vital things that you must consider before using ASP.NET as your web development tool.

1. High-grade scalability

For being able to make the most of a web development framework, you must ensure that the same is equipped with high-end scalability options. The more scalable the framework is, the better it would be for you (as a developer) to manage the events and sessions across multiple servers used during web development.

If your web programming framework comes with top-level scalability, you can stop worrying about scaling your web application in accordance to forthcoming advancements in the field of technology. ASP.NET features such as pipeline optimization and process configuration aid you in addressing the varying requirements as your project scales from one stage to another.  

2. An efficient web server

The prime reason behind the increased use of ASP.NET is its excellent web server efficiency. Backed by a brilliant web server, ASP.NET enables you to deal with different web development scenarios in addition to offering you the flexibility of monitoring web pages, modules and specific components. To sum it up, with ASP.NET, you need not stress about the speed of the web server because the framework handles the dedicated memory which is required for building web applications and further protecting the application from a wide array of irregularities and security infringements that might occur during the development process. 

3. Commendable speed

Speed is something that can render more power and authority to the web developers. If you are going with ASP.NET, you can expect quick and prompt arrangement of controls and facilities. Equipped with tables, easy-to-handle grids and wizards, ASP.NET offer you a suite of navigation, allowing you to execute web development projects smoothly. Eliminating the need for configuring a web server, ASP.NET permits you to get started with the app coding process rightaway.

Since ASP.NET runs on its own web server, you need not worry about configuring a new server on your system. The framework automatically spins a web server for your use. This is indeed a feature unavailable in a variety of other web app programming frameworks.

4. Lesser coding

Unlike a wide collection of web app development frameworks, ASP.NET comes with brilliant functional capabilities, thereby eliminating the need for any lengthy and complex coding. Features such as:WYSIWYG editing, drag-and-drop server controls and multi-lingual support make ASP.NET a framework worth working with. These features make ASP.NET a viable option for both professionals as well as the beginners who’ve just started using the framework for developing out-of-the-box web applications.

5. Trustworthy and consistent

With authentication and data validation serving as two strong assets of ASP.NET, it won’t be wrong to call it as one of the most reliable web development systems. Rich in streamlined components, ASP.NET allows a web program to automatically detect and recover from bugs, followed by acting in the right way. Issues such as crash protection, dead locks and memory leaks are being addressed well by ASP.NET.

As a web developer, you’ll no longer have to worry about system exceptions and all the scrubbing incoming data during web app development. ASP.NET is already designed to handle all this and much more for you. All you need to do is delve into some easy coding and you’re done with building a perfect web solution.

Wrapping it all up

The aforementioned pointers are just the tip of an iceberg. There’s a lot more to explore with the ASP.NET programming framework. If you’re looking forward to develop rich and expensive web applications then ASP.NET is the platform you can choose without giving a second thought. Looking at the ever-growing demands of today’s clients, ASP.NET is the tool that will help you meeting every type of web app development requirement.

Create Dynamic Menu in ASP.NET MVC – A Complete How to Guide


A menu plays a significant role in lending an amazing UX by making an application easily navigable. It can be used to make accessibility to a particular section a breeze.If you want to ensure a surefire application, it is essential that elements of your application must be accessed with ease. It must appear intuitive and intriguing, so that users can execute them with a flair. You may create multiple modules within a project and depending upon the user’s permissions, an appropriate menu can be implemented dynamically via ASP.NET.

ASP.NET is an open source server side framework that augments web app development with great efficiency and precision. It is the core of the popular Content Management Systems (CRM), eCommerce, and so forth that deliver utile features.

Here is a comprehensive guide that offers a complete tutorial for creating a user-friendly dynamic menu via ASP.NET MVC. The process is extremely simple with only 5 easy steps at a glance.

Let’s distill the process and explore how dynamic menus can be created efficiently.

Create Dynamic Menu in ASP.NET MVC

Step 1: Create a database table

To create dynamic menus in ASP.NET MVC, the very first step is to generate a database table that can hold all the menu items in a designed hierarchy (if any). The database table can be created with a simple query as mentioned below.

Create Table Menus(ID int Primary Key Identity(1,1), ParentID int foreign key References Menus(ID), Title varchar(50), Description varchar(250))

This query will create a table Menus that will hold four values. These values are:

ID: is the primary key and auto generated
Parent ID: is the foreign key
Title: Name of the field
Description: is the information that you want to display when a user hovers over the menu.

With this, a desired table will be created in the database.

Step 2: Insert values into the table

A simple insert query can be used for adding the data into the table. Now, there are two possibilities, that is, your menu may possess multiple parent items that further possess child items or there may be parent items only. So, you must insert the values as per your app requirements.

Query to insert values into the table Menus.

Insert Into Menus(null, ‘Item One’, ‘Desc’) // First Parent Item
Insert Into Menus(null, ‘Item Two, ‘Desc’) // Second Parent Item
Insert Into Menus(null, ‘Item Three’, ‘Desc’) // Third Parent Item
 
Insert Into Menus(1, ‘Item Sub One’, ‘Desc’) // Child of First Parent Item
Insert Into Menus(2, ‘Item Sub Two’, ‘Desc’) // Child of Second Parent Item
Insert Into Menus(3 ‘Item Sub Three’, ‘Desc’) // Child of Third Parent Item

By implementing the above mentioned queries, your Menus table will contain three items in the Menu and each item will further have a child item.

Step 3: Fetch the data from the table

Now, the next step is to fetch the menu items from the table Menus that was created in the step 1, and return a list of all the items.

For this, a GetMenus() function is created in MyMenu class. In this function, there is a loop that will help fetch the items of the Menu and return them via a list. The lines of code for the same is as follows.

Code Snippet for model:

public static class MyMenu
{
   /// <summary>
   /// Get List of All Menu Items from Database
   /// </summary>      
   /// <returns>Returns List<Menus> object</returns>
   public static List<Menus> GetMenus()
   {
       using(var context = new ProjectEntities())
       {
            return context.Menu.ToList();
        }
    }
}

Step 4: Display the created menu on the screen

Now, when the Menu items has been fetched from the database, it is the time to represent it in the view.

Code Snippet for View:

@{
    List<Menus> myMenu = MyMenu.GetMenus();
    var plist = myMenu.Where(m => m.ParentID == null).ToList(); // This will list main menu items on which we’ll apply loop to display them.
    if (plist != null && plist.Count > 0)
    {
        <ul class=”nav”>
        @foreach (var pitem in plist)
        {
            <li>
                <a href=”{URL-Required} title=”@Description”>@pitem.Title</a>
                @{
                    var clist = myMenu.Where(m => m.ParentID == pitem.ID).ToList();
                    if (clist != null && clist.Count > 0)
                    {
                        <ul>
                            @foreach (var citem in clist)
                            {
    <li><a href=”{URL-Required}”title=”@Description”>@citem.Title</a></li>
                            }
                        </ul>
                    }
                }
            </li>
        }
        </ul>
    }
}

Here, ui and li HTML tags are used in the loop. This will help display the created menu in the view. Now, move to the next step.

Step 5: Beautify the menu to make it appear captivating

To ensure an enticing and easily readable menu, it is essential to make it appear visually appealing and intriguing. You may use the CSS appropriately to enhance the look and feel of the menu in a desired fashion. Here, I have incorporated the following chunk of code in the CSS file to boost the navigation ease and ensure an attractive Menu.

Code Snippet CSS:

ul, ol, li {list-style: outside none none;}
.nav {float: left;padding: 0;background-color: #5eab1f;}
.nav li {display: inline-block;position: relative;vertical-align: middle;}
.nav li:hover, .nav li.active {background-color: #4c9312;}
.nav li a {color: #fff;float: left;font-size: 15px;padding: 16px 14px; text-decoration: none;}
.nav li ul {background-color: #fff;border-radius: 0 0 5px 5px;box-shadow: 0 2px 3px #000;display: none;min-width: 200px;padding: 20px 0;position: absolute;top: 48px;z-index: 9999;}
.nav li ul:before {border-bottom: 8px solid #fff;border-left: 8px solid transparent;border-right: 8px solid transparent;content: “”;left: 28%;position: absolute;top: -8px;}
.nav ul li {float: left;width: 100%;}
.nav ul li a {color: #333;float: left;font-size: 15px;padding: 10px 5%;width: 90%;}
.nav li:hover, .nav li.active {background-color: #4c9312;}

This CSS has been created considering a few requirements, you may develop it in a desired fashion to bring substantial changes in the visual appearance. Therefore, you may streamline the CSS as per your UX and design needs.

Wrapping Up

By following this absolute guide, you can efficiently create beautiful dynamic menus via the ASP.NET MVC. It is advisable to thoroughly go through each step and design desirable menu while ensuring utmost navigation ease.