Sunday, May 19, 2019

Registering Service using Asp.Net Core Dependency Injection

Asp.Net Core provides built in support for Dependency Injection, we can register classes in the Application startup and inject instances of these classes wherever required like controller, views or other classes.

ASP.NET Core provides a built-in service container IServiceProvider to register class dependency. Services are registered in the Startup using the ConfigureServices method.

In previous examples we used to connect to the Database directly from the Controller layer, however in larger applications it is recommended to use a Service / Repository layer to interact with the database. Let us create a simple service class which will do the database operations, we will register this service in the Startup and inject this service in the controller using Asp.Net Core Dependency Injection.

Dependency Injection in Asp.Net Core

Dependency Injection is a design pattern which helps eliminate dependency between various classes and modules in a larger application. Dependency Injection aims in creating dependent objects for a class outside the class and injecting them dynamically into the class, instead of instantiating the dependent classes inside the main class. By doing this Dependency Injection helps us develop Applications with better modularity and test-ability.

Asp.Net Core provides built in dependency injection support for applications, in previous versions of Asp.Net dependency injection was implemented using 3rd party libraries like StructureMap, Unity etc. ASP.NET Core provides a built-in service container, IServiceProvider. Services are registered in the app's Startup.ConfigureServices method.

In Asp.Net Core a dependent service is registered with the service container in the ConfigureServices method of the Startup class as follows.

Saturday, May 18, 2019

ViewModel, Partial Views and Layouts in Asp.Net Core

Entity Framework Core with Asp.Net MVC Core Getting Started

Layout in Asp.Net Core MVC Views

Every page on a website will have some common elements like Header, Logo, Menu, Navigation links etc. A layout helps to create a common view for these re-usable part of the page and use it in each page of the application.

A layout is also a view with .cshtml extension. The layout view defines the header, content area and the footer sections. In general re-usable content is placed in the header and footer sections, the content section varying content of the pages. The content section contains a statement @RenderBody(), which embeds the varying content of each page in the content section.

A typical layout view page looks like this.