2. Prerequisite - Dependency injection (DI)
• Dependency injection (DI) is a technique for achieving loose coupling
between objects and their collaborators, or dependencies. Rather
than directly instantiating collaborators, or using static references, the
objects a class needs in order to perform its actions are provided to
the class in some fashion.
• Most often, classes will declare their dependencies via their
constructor, allowing them to follow the Explicit Dependencies
Principle. This approach is known as "constructor injection"
3. Prerequisite - Dependency Inversion Principle
(DIP)
• The Dependency Inversion Principle (DIP) states that high level
modules should not depend on low level modules; both should
depend on abstractions (typically interfaces). Abstractions should not
depend on details.
• Details should depend upon abstractions which are provided to them
when the class is constructed.
4. Prerequisite - containers
• A container is essentially a factory that's responsible for providing
instances of types that are requested from it.
• When a system is designed to use DI, with many classes requesting
their dependencies via their constructor (or properties), it's helpful to
have a class dedicated to creating these classes with their associated
dependencies. These classes are referred to as containers, or more
specifically, Inversion of Control (IoC) containers or Dependency
Injection (DI) containers.
5. What is ASP.NET Core?
• A new free, open-source, high-performance and cross-platform
framework for building modern cloud-based Web applications using
.NET
• ASP.NET Core is a modular framework distributed as NuGet packages.
This allows us to include packages that are required in our
application.
6. ASP.NET Core
• ASP.NET Core is designed to be deployed on cloud as well as on-
premises. Developers can now build cloud-based web applications, IoT
(Internet of Thing) and mobile backend applications using ASP.NET
Core framework which can run on Windows, Linux, and Mac operating
systems.
• ASP.NET Core Version History
Version Release Date
ASP.NET Core 2.0 August 2017
ASP.NET Core 1.1 November 2016
ASP.NET Core 1.0 June 2016
7. .NET Core != ASP.NET Core
• ASP.NET Core and .NET Core are not the same. They are different, just
like ASP.NET and .NET Framework are different.
• .NET Core is a fast, lightweight, modular and open source framework
for creating web applications and services that run on Windows, Linux
and Mac. So, it is a platform on which ASP.NET Core application runs.
• .NET Core is named "Core" because it includes core features of the
.NET framework.
8. .NET Core components
• ASP.NET Core is a part of .NET Core SDK so you don't need to install ASP.NET Core
separately.
• .NET Core comes under Apache 2 licenses. Visit .NET Core repository on Github to
contribute or download the source code.
9. Why ASP.NET Core?
• Supports Multiple Platforms: ASP.NET Core applications can run on
Windows, Linux, and Mac. So you don't need to build different apps
for different platforms using different frameworks.
• Fast - 8x Faster than Node; 3x Faster than Go .. ASP.NET Core no
longer depends on System.Web.dll for browser-server
communication. ASP.NET Core allows us to include packages which
we need for our application. This reduces the request pipeline and
improves the performance and scalability.
• IoC Container: It includes built-in IoC container for automatic
dependency injection which makes it maintainable and testable.
• Open-Source with Contributions – even the docs
10. Why ASP.NET Core?
• Integration with Modern UI Frameworks: It allows you to use and
manage modern UI frameworks such as AngularJS, ReactJS, Umber,
Bootstrap etc. using Bower (a package manager for the web).
• Smaller Deployment Footprint: ASP.NET Core application runs on
.NET Core which is smaller than full .NET Framework. So, the
application which uses only a part of .NET CoreFX will have smaller
deployment size. This reduces the deployment foot print.
• Hosting: ASP.NET Core web application can be hosted on multiple
platforms with any web server such as IIS, Apache etc. It is not
dependent only on IIS as a standard .NET Framework.
• Choice of Tools and Editors – Any Text Editor plus CLI, or Visual Studio
12. ASP.NET Core ASP.NET
Build for Windows, macOS, or Linux Build for Windows
Razor Pages is the recommended approach to
create a Web UI as of ASP.NET Core 2.x. See
also MVC, Web API, and SignalR.
Use Web Forms, SignalR, MVC, Web API, or Web
Pages
Develop with Visual Studio, Visual Studio for Mac,
or Visual Studio Code using C# or F#
Develop with Visual Studio using C#, VB, or F#
Higher performance than ASP.NET Good performance
Choose .NET Framework or .NET Core runtime Use .NET Framework runtime
14. .NET Core Runtime
• .NET Core SDK can be installed on the platform you are using such as
Windows, Linux or Mac.
• .NET Core Runtime and .NET Core SDK are different things.
• .NET Core Runtime is only used to run .NET Core application whereas
.NET Core SDK includes tools and libraries to develop .NET Core
applications.
17. Command-line Interface (CLI)
• If you do not use Visual Studio for .NET core application development for
some reason and want to use different IDE then you can use command-line
interface to create, compile, build, restore and run .NET Core application.
• .NET Core SDK installation also installs command-line interface for the
selected platform. It installs the latest stable version of the tools and put
them on your PATH so you can run dotnet from the Console.
• .NET Core command-line interface (CLI) tools
https://docs.microsoft.com/en-us/dotnet/core/tools/?tabs=netcore2x
• Getting started with .NET Core using the command line
https://docs.microsoft.com/en-us/dotnet/core/tutorials/using-with-xplat-cli
19. File > New Project > Web
• ASP .NET Core Web App
• Web App (4.x)
20. Select a Template
1.0 , 1.1, 2.0 Templates
• Empty
• Web API
• Web App (Razor)
• Web App (MVC)
• Angular
• React.js
• React.js & Redux
Other settings:
• Authentication
• Docker Support
21. ASP.NET Core Project Structure (Empty Project )
We can change it to folder view by clicking Solution
and Folders icon.
ASP.NET Core project files and folders are
synchronized with physical files and folders.
22. Dependencies
• The Dependencies in the ASP.NET Core 2.0 project contain all the
installed server-side NuGet packages as well as client-side
frameworks such as jQuery, AngularJS, Bootstrap etc. These client-
side dependencies are managed using Bower in Visual Studio.
23. Bower “A package manager for the web”
• Bower calls itself "A package manager for the web". Within the .NET
ecosystem, it fills the void left by NuGet's inability to deliver static content
files
• New projects created with the ASP.NET Core project templates set up the
client-side build process. jQuery and Bootstrap are installed, and Bower is
supported.
• Client-side packages are listed in the bower.json file. The ASP.NET Core
project templates configures bower.json with jQuery, jQuery validation, and
Bootstrap.
24. Properties
• The Properties node includes launchSettings.json file which includes
Visual Studio profiles of debug settings. The following is a default
launchSettings.json file.
Edit debug settings from the
debug tab of project
properties.
Right click on the project -> select
Properties -> click Debug tab.
26. wwwroot
• wwwroot folder is treated as a web root folder. Static files can be
stored in any folder under the web root and accessed with a relative
path to that root.
• only files that are in wwwroot folder can be served over an http
request. All other files are blocked and
cannot be served by default.
27. wwwroot
• Generally, there should be separate folders for the different types of
static files such as JavaScript, CSS, Images, library scripts etc
• You can access static files with base URL and file name.
For example, we can access site.css file in the css folder
by http://localhost:<port>/css/app.css.
• you need to include a middleware for serving static files in the
Configure method of Startup.cs.
28. Program.cs
• ASP.NET Core web application is actually a console project which
starts executing from the entry point public static void Main() in
Program class where we can create a host for the web application.
• The steps for creating a host in ASP.NET Core 1.x is different in
ASP.NET Core 2.x.
30. • The WebHostBuilder class is the helper class to create and configure a
host for a web application.
• The UseKestrel() method is an extension method which specifies Kestrel
as an internal web server.
• The Kestrel is an open-source, cross-platform web server for ASP.NET
Core. It is designed to be used behind proxy because it has not yet
matured to be exposed as a full-fledge web server.
• ASP.NET Core application can be a cross-platform application so it can be
used with any web server, and not only IIS.
• There will be an external web server such as IIS, Apache, Nginx etc. which
will dispatch http requests to the internal web server Kestrel.
31. • The UseContentRoot() method specifies the current directory as a root
directory which will be src folder in the default ASP.NET Core project.
• The UseIISIntegration() method specifies the IIS as the external web server or
the reverse proxy server.
• The UseStartup<startup>() method specifies the Startup class to be used by
the web host. Startup class is like Global.asax of .NET framework where you
can configure request pipeline (middleware).
• The Build() method returns an instance of IWebHost using the configuration
specified above.
• The Run() method starts the web application and blocks the calling thread till
the host is shutdown
The command line application will become web application from this point onwards.
33. Startup Class
• ASP.NET Core application must include Startup class. It is like
Global.asax in the traditional .NET application.
• Startup class includes two public methods
ConfigureServices and Configure.
34. Startup ConfigureServices
• The Dependency Injection pattern is used heavily in ASP.NET Core
architecture.
• ConfigureServices includes built-in IoC container to provide dependent
objects using constructors.
• you can register your dependent classes with the built-in IoC container
using IServiceCollection.
• After registering dependent class, it can be used anywhere in the
application. You just need to include it in the parameter of the
constructor of a class where you want to use it. The IoC container will
inject it automatically.
• You can Configure third-party container like StructureMap, Unity, Autofac, Ninject,
Castle Windsor, etc.
35. Dependency Injection in ASP.NET Core
• ASP.NET Core is designed from scratch to support Dependency
Injection.
• ASP.NET Core injects objects of dependency classes through
constructor or method by using built-in IoC container.
• The built-in container is represented by IServiceProvider
implementation that supports constructor injection by default. The
types (classes) managed by built-in IoC container is called services.
• Framework Services: Services which are a part of ASP.NET Core framework
such as IApplicationBuilder, IHostingEnvironment, ILoggerFactory etc.
• Application Services: The services (custom types or classes) which you as a
programmer create for your application.
37. Service lifetimes and registration options
• Transient
Transient lifetime services are created each time they're
requested. This lifetime works best for lightweight, stateless services.
• Scoped
Scoped lifetime services are created once per request.
• Singleton
Singleton lifetime services are created the first time they're
requested (or when ConfigureServices is run if you specify an instance
there) and then every subsequent request will use the same instance.
38. Startup.Configure
• The Configure method is a place where you can configure application
request pipeline for your application using IApplicationBuilder instance that
is provided by the built-in IoC container.
• ASP.NET Core introduced the middleware components to define a request
pipeline, which will be executed on every request.
• You include only those middleware components which are required by your
application and thus increase the performance of your application.
• At run time, the ConfigureServices method is called before the Configure
method. This is so that you can register your custom service with the IoC
container which you may use in the Configure method.
39. Middleware “Built-in and Custom”
A middleware is nothing but a component (class) which is executed on
every request in ASP.NET Core application.
It can be either framework provided middleware, added via NuGet or
your own custom middleware.
• Each component in the pipeline is a request delegate.
• Each delegate can invoke the next component in the chain, or short-
circuit, returning back up the call chain
42. built-in middleware
Middleware Description
Authentication Adds authentication support.
CORS Configures Cross-Origin Resource Sharing.
Routing Adds routing capabilities for MVC
Session Adds support for user session.
StaticFiles Adds support for serving static files and directory browsing.
Diagnostics Adds support for reporting and handling exceptions and errors.
MVC Adds support for using MVC pattern
43. Diagnostics Middleware
Middleware Extension Method Description
DeveloperExceptionPageMiddleware UseDeveloperExceptionPage() Captures synchronous and
asynchronous exceptions from the
pipeline and generates HTML error
responses.
ExceptionHandlerMiddleware UseExceptionHandler() Catch exceptions, log them and re-
execute in an alternate pipeline.
StatusCodePagesMiddleware UseStatusCodePages() Check for responses with status codes
between 400 and 599.
WelcomePageMiddleware UseWelcomePage() Display Welcome page for the root path.
48. UseStaticFiles Middleware
• For the wwwroot folder
app.UseStaticFiles();
• For your own folder
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), “your own folder path")),
RequestPath = "/StaticFiles“ // URLrequest path
});
51. appsettings.json - project.json
• The project.json file includes settings for an application which is used
by .NET Core CLR (runtime) to determine how to run an application.
54. Working With a Database Using EF Core
• Add Entity Framework Core (EF Core) in ConfigureServices:
• Also supports InMemory – Install this package:
and modify ConfigureServices:
55. Working with EF Core’s AppDbContext
• Never directly instantiate your application’s DbContext type(s)
• Instead, request from DI using constructor parameters
Recommendation
• Follow the Dependency Inversion Principle and avoid having UI types
depend on details
• Using Entity Framework Core is an implementation detail
• Instead depend on an abstraction over your persistence method
• Common pattern for this: Repository
57. Razor Pages
• Razor Pages is an exciting new product released with ASP.NET Core 2,
which makes building webpages without an MVC framework quick
and easy.
• Razor Pages is a new feature of ASP.NET Core that makes coding
page-focused scenarios easier and more productive.
• The most importantly thing to know about Razor Pages is that they
are built on top of ASP.NET Core MVC, not beside it, and so all the
goodness from ASP.NET MVC applications (routing, ModelState, etc.)
you can still access in Razor Pages apps.
58. Razor Pages
• All of the Razor Pages types and features live in the
Microsoft.AspNetCore.Mvc.RazorPages assembly.
• The MVC package – Microsoft.AspNetCore.Mvc includes the Razor
Pages assembly.
• That means that you can use Razor Pages out of the box with MVC.
59. HOW?
• If you want to build few simple pages with MVC, you have controller
actions in separate place, HTML for view in separate place, ViewModel in a
different location, routes in separate place, and that just seems like too
much.
• With Razor Pages, you have this one Razor file (.cshtml), and the code for a
single page lives inside of that file, and that file also represents the URL
structure of the app . Therefore, you got everything inside of one file, and it
just works.
• However, you CAN separate your code to the code behind file
with .cshtml.cs extension. You would usually have your view model and
handlers (like action methods in MVC) in that file and handle the logic
there.
60. Creating Razor Pages app
• With VS 2017 and .NET Core 2 SDK installed if we follow the old
standard path in Visual Studio: File -> New Project -> Web -> ASP.NET
Core Web Application we will get the following screen:
61. Project files and folders
File or folder Purpose
wwwroot Contains static files. See Work with static files.
Pages Folder for Razor Pages.
appsettings.json Configuration
Program.cs Hosts the ASP.NET Core app.
Startup.cs Configures services and the request pipeline.
See Startup.
62. The Pages folder
• The _Layout.cshtml file contains common HTML elements (scripts and stylesheets) and
sets the layout for the application.
• The _ViewStart.cshtml sets the Razor Pages Layout property to use the _Layout.cshtml
file.
• The _ViewImports.cshtml file contains Razor directives that are imported into each Razor
Page.
• The _ValidationScriptsPartial.cshtml file provides a reference to jQuery validation scripts.
• The About, Contact and Index pages are basic pages you can use to start an app. The
Error page is used to display error information.
63. Configure bundling and minification
• The MVC and Razor Pages project templates provide
a bundleconfig.json configuration file which defines the options for
each bundle.
• By default, a single bundle configuration is defined for the custom
JavaScript (wwwroot/js/site.js) and stylesheet (wwwroot/css/site.css)
files
• https://docs.microsoft.com/en-us/aspnet/core/client-side/bundling-
and-minification
65. @page Directive
• @page makes the file into an MVC action - which means that it
handles requests directly, without going through a controller.
• @page must be the first Razor directive on a page.
• the PageModel class file has the same name as the Razor Page file
with .cs appended
66. Determine URL paths to pages
• The associations of URL paths to pages are determined by the page's
location in the file system.
• The runtime looks for Razor Pages files in the Pages folder by default.
• Index is the default page when a URL doesn't include a page.
File name and path matching URL
/Pages/Index.cshtml / or /Index
/Pages/Contact.cshtml /Contact
/Pages/Store/Contact.cshtml /Store/Contact
/Pages/Store/Index.cshtml /Store or /Store/Index
67. URL generation for Pages -Example
• URL generation for pages supports relative names.
• The following table shows which Index page is selected with different
RedirectToPage parameters from Pages/Customers/Create.cshtml
RedirectToPage(x) Page
RedirectToPage("/Index") Pages/Index
RedirectToPage("./Index"); Pages/Customers/Index
RedirectToPage("../Index") Pages/Index
RedirectToPage("Index") Pages/Customers/Index
RedirectToPage("Index"),
RedirectToPage("./Index"), and
RedirectToPage("../Index") are relative
names.
The RedirectToPage parameter is
combined with the path of the current
page to compute the name of the
destination page.
68. PageModel
• the PageModel class is called <PageName>Model and is in the same
namespace as the page.
• The PageModel class allows separation of the logic of a page from its
presentation.
• It defines page handlers for requests sent to the page and the data
used to render the page.
• You can add handler methods for any HTTP verb. The most common
handlers are:
• OnGet to initialize state needed for the page.
• OnPost to handle form submissions.
69. [BindProperty]
• Razor Pages, by default, bind properties only with non-GET verbs.
Binding to properties can reduce the amount of code you have to
write. Binding reduces code by using the same property to render
form fields.
• To bind a property on GET requests, set the [BindProperty] attribute's
Supports Get property to true: [BindProperty(SupportsGet = true)]
70. Customizing Routing - @page "{id:int}"
• The routing constraint"{id:int}" tells the page to accept requests to
the page that contain int route data.
• If a request to the page doesn't contain route data that can be
converted to an int, the runtime returns an HTTP 404 (not found)
error.
• To make the ID optional, append ? to the route constraint: @page
"{id:int?}"
71. Multiple handlers per page
• The asp-page-handler attribute is a companion to asp-page. asp-
page-handler generates URLs that submit to each of the handler
methods defined by a page.
The preceding code uses named handler methods.
Named handler methods are created by taking the text in
the name after On<HTTP Verb> and before Async
(if present)
72. Configuration and settings
• you can use the RazorPagesOptions to set the root directory for
pages, or add application model conventions for pages.
73. Custom root directory
• Add WithRazorPagesRoot to AddMvc to specify that your Razor Pages
are at a custom root directory in the app (provide a relative path):
74. Browser Link in ASP.NET Core
• Browser Link is a feature in Visual Studio that creates a
communication channel between the development environment and
one or more web browsers. You can use Browser Link to refresh your
web application in several browsers at once, which is useful for cross-
browser testing.
• Configuration
In the Configure method of the Startup.cs file:
app.UseBrowserLink();
75. How to use Browser Link
From the Browser Link toolbar control, you can:
• Refresh the web application in several browsers at once.
• Open the Browser Link Dashboard.
• Enable or disable Browser Link. Note: Browser Link is disabled by default in
Visual Studio 2017 (15.3).
• Enable or disable CSS Auto-Sync.
76. Open multiple browsers at once
To open multiple browsers at once, choose Browse with... from the same
drop-down. Hold down the CTRL key to select the browsers you want, and
then click Browse
77. Enable or disable CSS Auto-Sync
• When CSS Auto-Sync is enabled, connected browsers are
automatically refreshed when you make any change to CSS files.
How does it work?
Browser Link uses SignalR to create a communication channel between
Visual Studio and the browser.
When Browser Link is enabled, Visual Studio acts as a SignalR server
that multiple clients (browsers) can connect to.
Browser Link also registers a middleware component in the ASP.NET
request pipeline. This component injects special <script> references
into every page request from the server.
78. Tag Helpers
• Tag Helpers enable server-side code to participate in creating and rendering
HTML elements in Razor files.
• Replaces HTML Helpers (still available, but not recommended)
• Render within HTML tags
• A rich IntelliSense environment for creating HTML and Razor markup
• There are many built-in Tag Helpers for common tasks - such as creating forms,
links, loading assets and more
• @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
• https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-
in/index?view=aspnetcore-2.0
79. Managing Tag Helper scope
• Tag Helpers scope is controlled by a combination of @addTagHelper,
@removeTagHelper, and the "!" opt-out character.
• @addTagHelper makes Tag Helpers available.
• @removeTagHelper removes Tag Helpers.
• You can disable a Tag Helper at the element level with the Tag Helper
opt-out character ("!")
<!span asp-validation-for="Email" class="text-danger"></!span>
80. IntelliSense support for Tag Helpers
• When you create a new ASP.NET web app in Visual Studio, it adds the
NuGet package "Microsoft.AspNetCore.Razor.Tools". This is the
package that adds Tag Helper tooling
82. Author Tag Helpers
• A tag helper is any class that implements the ITagHelper interface.
However, when you author a tag helper, you generally derive from
TagHelper, doing so gives you access to the Process method.
• Add the yourTagHelper class to the TagHelpers folder.
• To make the yourTagHelper class available to all our Razor views, add
the addTagHelper directive to the Views/_ViewImports.cshtml .
83. Razor Pages
• Razor Pages are Page focused way of programming web sites
• You can(if you want to) have all the code and HTML in one place
• The location of Razor page file determines the URL/route for your page
• Razor Pages are not a reincarnation of old ASP.NET Web Pages
• Features that we can use with MVC we can also use with Razor Pages:
• Model Binding
• Razor support
• Tag Helpers
• HTML Helpers
• Handlers (Action Methods)
• etc..
• We have handlers (OnGet, OnGetAsync, OnPostAsync etc..)
• Location of the page in file system (project structure) determines the URL path
• Need to have one root folder
• Stored in Pages root folder by default (configurable)
85. ASP.NET Core MVC with EF Core
• EF Core 2.0 is the latest version of EF but doesn't yet have all the
features of EF 6.x.
• To add EF Core support to a project, install the database provider that
you want to target. This tutorial uses SQL Server, and the provider
package is Microsoft.EntityFrameworkCore.SqlServer. This package is
included in the Microsoft.AspNetCore.All metapackage, so you don't
have to install it.
• This package and its dependencies (Microsoft.EntityFrameworkCore
and Microsoft.EntityFrameworkCore.Relational) provide runtime
support for EF.
87. Working With a Database Using EF Core
• Add Entity Framework Core (EF Core) in ConfigureServices:
• Also supports InMemory – Install this package:
and modify ConfigureServices:
88. Using EF Core’s AppDbContext
• 1- install Entity Framework Core NuGet packages.
• 2- Create the data model
• 3- Create the Database Context
• 4-Add your connection string in appsettting.json
• 5- Register the context with dependency injection
• 6-Add Migration and Update Database.
89. Working with EF Core’s AppDbContext
• Never directly instantiate your application’s DbContext type(s)
• Instead, request from DI using constructor parameters
Recommendation
• Follow the Dependency Inversion Principle and avoid having UI types
depend on details
• Using Entity Framework Core is an implementation detail
• Instead depend on an abstraction over your persistence method
• Common pattern for this: Repository
90. Loading Related Data
Entity Framework Core allows you to use the navigation properties in your
model to load related entities. There are three common O/RM patterns used
to load related data.
• Eager loading means that the related data is loaded from the database as
part of the initial query.
• Explicit loading When the entity is first read, related data isn't retrieved.
You write code that retrieves the related data if it's needed.
• Lazy loading When the entity is first read, related data isn't retrieved.
However, the first time you attempt to access a navigation property, the
data required for that navigation property is automatically retrieved.
91. Eager loading
• You can use the Include method to specify related data to be included
in query results.
• You can include related data from multiple relationships in a single
query.
92. Including multiple levels -Eager loading
• You can drill down thru relationships to include multiple levels of
related data using the ThenInclude method.
• Note: Visual Studio offer incorrect code completion options when
using the ThenInclude This is a symptom of an IntelliSense bug . It is
safe to ignore these spurious syntax errors as long as the code is
correct and can be compiled successfully.
93. Explicit loading
• This feature was introduced in EF Core 1.1.
• When the entity is first read, related data isn't retrieved. You write
code that retrieves the related data if it's needed.
• you can use the Load method to do explicit loading.
94. Lazy loading
• This feature was introduced in EF Core 2.1.
• The simplest way to use lazy-loading is by installing the
Microsoft.EntityFrameworkCore.Proxies package and enabling it with
a call to UseLazyLoadingProxies when using AddDbContext:
EF Core will then enable lazy-loading for any navigation property that
can be overridden--that is, it must be virtual and on a class that can be
inherited from.
95. Performance considerations
• If you know you need related data for every entity retrieved, eager
loading often offers the best performance, because a single query
sent to the database is typically more efficient than separate queries
for each entity retrieved.
• In some scenarios separate queries is more efficient. Eager loading of
all related data in one query might cause a very complex join to be
generated, which SQL Server can't process efficiently.
96. Repository Pattern In ASP.NET Core MVC And
Entity Framework Core
The repository pattern is intended to create an Abstraction layer
between the Data Access layer and Business Logic layer of an
Application. It is a data access pattern that prompts a more loosely
coupled approach to data access. We create a generic repository, which
queries the data source for the data, maps the data from the data
source to a business entity and persists changes in the business entity
to the data source
97. WHY?
• We implement repository pattern to develop a loosely coupled application.
It makes the code more testable. It creates an abstraction layer between
ORM and business logic layer of the application.
• the repository mediates between the data source layer (Entity Framework)
and the business layer (Controller) of the application. It performs
operations as following way.
• It queries the underlying data source (database) for the data.
• It maps the data from the data source to a business entity that uses to create the
database.
• It persists changes in the business entity to the data source.
98. Advantages of Repository Pattern
It has some advantages which are as follows:
• An entity might have many operations which perform from many locations
in the application, so we write logic for common operations in the
repository. These operations might be Create, Read, Update, Delete,
Search, Filter, Sort, Paging, and Caching etc.
• The Entity Framework is not testable out of the box. We have to create
mock classes to test it. Data access logic can be tested using repository
pattern.
• As business logic and data access logic separate in the repository pattern
that’s why it easy to manage and readable. It reduces development as well
me, as common functionality logic writes once in the application.
99. How? “Employee Entity”
• ASP.NET Core is designed to support dependency injection. So, we
create a repository interface named IEmployeeRepository for
Employee .
• This interface has definitions of all methods to perform CRUD
operations on the Employee entity.
• let’s implement the preceding interface on a class named
EmployeeRepository.
• This class has implemention of all methods to perform CRUD
operations on the Employee entity. It has a parameterized constructor
that accepts Context as a parameter. It passes at a time of repository
instance creates by dependency injection.
100. How? “Employee Entity” cont..
• web application communicates to data access layer via an interface so
we register repository to the dependency injection during the
application start up.
• Create Application User Interface
• create a view model named EmployeeViewModel for application UI
and CRUD operations. This model strongly binds with a view.
101. Routing to controller actions in ASP.NET Core
• Actions are either conventionally routed or attribute routed. Placing a
route on the controller or the action makes it attribute routed.
• With attribute routing the controller name and action names
play no role in which action is selected.
102. Attribute routing with Http[Verb] attributes.
• Attribute routing can also make use of the Http[Verb] attributes such
as HttpPostAttribute. All of these attributes can accept a route
template.
103. Token replacement in route templates
• For convenience, attribute routes support token replacement by
enclosing a token in square-braces ([, ]).
• No route Prefix.
106. IActionResult
there are a wide range of ways that you can return content from MVC
controllers that aren't limited to just ActionResults.
• ContentResult
• EmptyResult
• FileResult
• HttpStatusCodeResult
• JavaScriptResult
• JsonResult
• RedirectResult
• RedirectToRouteResult
107. View components in ASP.NET Core
• New to ASP.NET Core MVC, view components are similar to partial
views, but they're much more powerful. View components don't use
model binding, and only depend on the data provided when calling
into it.
A view component:
• Renders a chunk rather than a whole response.
• Includes the same separation-of-concerns and testability benefits found
between a controller and view.
• Can have parameters and business logic.
• Is typically invoked from a layout page.
108. Using of View components
View components are intended anywhere you have reusable rendering logic
that's too complex for a partial view.
• Dynamic navigation menus
• Tag cloud (where it queries the database)
• Login panel
• Shopping cart
• Recently published articles
• Sidebar content on a typical blog
• A login panel that would be rendered on every page and show either the
links to log out or log in, depending on the log in state of the user
109. Creating a view component
• A view component class can be created by Deriving from ViewComponent class.
• A view component defines its logic in an InvokeAsync method that returns an
IViewComponentResult.
• Parameters come from the calling method, not HTTP, there's no model binding
• The runtime searches for the view in the following paths:
• Views/<controller_name>/Components/<view_component_name>/<view_name>
• Views/Shared/Components/<view_component_name>/<view_name>
• The default view name for a view component is Default, which means your view file
will typically be named Default.cshtml.
• We recommend you name the view file Default.cshtml and use
the Views/Shared/Components/<view_component_name>/<view_name> path.
110. Invoking a view component
• To use the view component, call the following inside a view:
• Invoking a view component as a Tag Helper
In order to use a View Component as a Tag Helper, you must register the assembly containing the
View Component using the @addTagHelper directive
if your View Component is in an assembly called "MyWebApp", add the following directive to the
_ViewImports.cshtml file:@addTagHelper *, MyWebApp
111. Tag Helpers
• Tag Helpers enable server-side code to participate in creating and rendering
HTML elements in Razor files.
• Replaces HTML Helpers (still available, but not recommended)
• Render within HTML tags
• A rich IntelliSense environment for creating HTML and Razor markup
• There are many built-in Tag Helpers for common tasks - such as creating forms,
links, loading assets and more
• @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
• https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-
in/index?view=aspnetcore-2.0
112. Managing Tag Helper scope
• Tag Helpers scope is controlled by a combination of @addTagHelper,
@removeTagHelper, and the "!" opt-out character.
• @addTagHelper makes Tag Helpers available.
• @removeTagHelper removes Tag Helpers.
• You can disable a Tag Helper at the element level with the Tag Helper
opt-out character ("!")
<!span asp-validation-for="Email" class="text-danger"></!span>
113. IntelliSense support for Tag Helpers
• When you create a new ASP.NET web app in Visual Studio, it adds the
NuGet package "Microsoft.AspNetCore.Razor.Tools". This is the
package that adds Tag Helper tooling
115. Author Tag Helpers
• A tag helper is any class that implements the ITagHelper interface.
However, when you author a tag helper, you generally derive from
TagHelper, doing so gives you access to the Process method.
• Add the yourTagHelper class to the TagHelpers folder.
• To make the yourTagHelper class available to all our Razor views, add
the addTagHelper directive to the Views/_ViewImports.cshtml .
116. References
• ASP .NET: http://www.asp.net
• .NET Core: https://www.microsoft.com/net
• .NET Web Dev Blog: https://blogs.msdn.microsoft.com/webdev
• Scott Hanselman’s Blog: https://www.hanselman.com/blog
• .NET Conf: http://www.dotnetconf.net
• MSDN Channel 9: https://channel9.msdn.com
• Tutorials: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-
mvc-app
• C# 7: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7
• ASP.NET Core Roadmap: https://github.com/aspnet/Home/wiki/Roadmap
117. References
• New Razor Pages: http://www.hishambinateya.com/welcome-razor-pages
• Intro to Razor: https://docs.microsoft.com/en-us/aspnet/core/mvc/razor-
pages
• Migrating from MVC to MVC Core:
https://docs.microsoft.com/enus/aspnet/core/migration/mvc
• .NET core : https://mva.microsoft.com/learning-path/aspnet-core-20-
23?MC=ASPNET
• Repository Pattern in ASP.Net Core mvc :
http://l-knowtech.com/2017/09/12/repository-pattern-asp-net-core-mvc-
entity-framework-core/
118. References
Try ASP.NET Core course:
https://www.codeschool.com/courses/try-asp-net-core
ASP.NET CoreQuick Start :
http://aspnetcorequickstart.com/
Razor Pages :
http://www.dotnet-stuff.com/tutorials/aspnet-core/introduction-to-razor-pages-in-
asp-net-core
Introduction to ASP.NET Core Razor Pages - Damian Edwards:
https://www.youtube.com/watch?v=yyBijyCI5Sk
Simpler ASP.NET Apps with Razor Pages :
https://msdn.microsoft.com/en-us/magazine/mt842512.aspx