Share
Embed
Cross-Plattform-Serveranwendungen mit ASP.NET Core
ASP.NET MVC, ASP.NET Web API und Entity Framework sind ein fester Bestandteil in der .NET-Welt wenn es um Websites, Bereitstellung von APIs und Datenbankzugriff geht. Allerdings fühlen diese Technologien sich nur auf Windows-Systemen so richtig heimisch. Mit dem neuen .NET Core erweitert Microsoft die Welt des .NET Frameworks. Neben Dependency Injection und dem Zugriff auf verschiedene Datenbank unter Verwendung von Entity Framework bringt das neue Open-Source Framework viele weitere interessante Neuerungen mit sich. Was die beste Neuerung ist? Als Cross-Plattform-Framework fühlt sich .NET nun auch auf Linux und macOS wie zu Hause.
GitHub: https://github.com/thinktecture/dotnet-summit-2017-asp-dot-net-core
Manuel Rauber
May 03, 2017
Transcript
70 slides
-
The guy who’s talkin’ Software Architect @ Thinktecture AG !
[email protected] " @manuelrauber # https://manuel-rauber.com Microsoft MVP Manuel Rauber ASP.NET Core Cross-Plattform-Serveranwendungen -
Target Architecture .NET Standard & .NET Core ASP.NET Core MVC
& Web APIs EntityFramework Core Cross-Plattform-Serveranwendungen ASP.NET Core Talking Points -
Time Doing 14:00 – 15:30 Part I 15:30 – 16:00
☕ & " 16:00 – 17:30 Part II Cross-Plattform-Serveranwendungen ASP.NET Core Timetable -
Overview Lightweight service-based architecture Functional services with dedicated interfaces
Use other services, like database or file system (JSON-based) HTTPS Web APIs Application push services via WebSocket SignalR Socket.io Cross-Plattform-Serveranwendungen ASP.NET Core Target Architecture HTTP HTTPS WebSocket Service A Service B Service C Web APIs (ASP.NET, Node.js, …) HTML5-Application (Single-Page Application) Web Cordova Electron -
“Behind the scenes” Functional services with dedicated interfaces Strict
REST services do not model real world Better: Design interfaces according to use case Single Web API can use multiple backend services (JSON-based) HTTPS Web APIs Embraces usage of common denominator Content Negotation HTTP Status Codes Resources are mapped to URLs Lightweight & scalable Cross-Plattform-Serveranwendungen ASP.NET Core Target Architecture HTTP HTTPS WebSocket Service A Service B Service C Web APIs (ASP.NET, Node.js, …) AuthN & AuthZ Client -
Challenges Mastering different kind of base class libraries Hard
to reuse skills Common denominator needed for code reusage Hard to reuse code Fiddling with a lot of interfaces ”Having fun with retargeting PCLs” J Implementation needed on each platform Cross-Plattform-Serveranwendungen ASP.NET Core .NET today -
Common denominator – Flashback 2014 Cross-Plattform-Serveranwendungen ASP.NET Core .NET today
Platform Code Interfaces All others: Shared code with platform switches -
One library to rule them all Cross-Plattform-Serveranwendungen ASP.NET Core .NET
tomorrow https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/ -
Benefits One base library to learn, not one per .NET
platform Easy code reuse due to a bigger API surface area .NET standard can be updated without having all platforms to be updated Faster and independent update cycles Cross-Plattform-Serveranwendungen ASP.NET Core .NET tomorrow -
What exactly is it? .NET Standard is an open source
specification: https://github.com/dotnet/standard Represents a common set of API to be implemented by all .NET platforms .NET Standard will replace PCLs .NET Standard 2.0 will be released in Q3 2017 Cross-Plattform-Serveranwendungen ASP.NET Core .NET Standard “.NET Standard solves the code sharing problem for .NET developers across all platforms by bringing all the APIs that you expect and love across the environments that you need: desktop applications, mobile apps & games, and cloud services.” - Immo Landwerth https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/ -
2.0 Differences to PCLs Portable Class Libraries .NET Standard Cross-Plattform-Serveranwendungen
ASP.NET Core .NET Standard Profile A Profile B Profile C Intersection Profile: Possible Platform targets … … 1.1 1.0 Higher versions are backwards compatible to lower versions. -
Versioning Additive: Higher versions incorporate all APIs from previous versions.
There are no breaking changes between versions Immutable: After shipping, the version is frozen Cross-Plattform-Serveranwendungen ASP.NET Core .NET Standard -
Versioning Higher version more capabilities more APIs
higher code reuse less platform support Lower version less capabilities less APIs (maybe) lower code reuse better platform support Cross-Plattform-Serveranwendungen ASP.NET Core .NET Standard -
Targeting Represented by NuGet package NetStandard.Library containing assembly netstandard.dll
in fact: everything’s a NuGet package within the new .NET Standard world Build Time .NET Standard bridges references to existing .NET Framework and PCL assemblies via type forwarding Run Time Each platform provides an implementation for netstandard.dll that type forwards to its own implementation Cross-Plattform-Serveranwendungen ASP.NET Core .NET Standard 2.0 -
Targeting @ Build Time Cross-Plattform-Serveranwendungen ASP.NET Core .NET Standard 2.0
Your .NET Standard-based Class Library .NET Framework or PCL netstandard.dll mscorlib.dll netstandard!Object mscorlib!Object Different Type Identities Type Forwarding https://www.slideshare.net/terrajobst/net-standard-under-the-hood -
Targeting @ Build Time Cross-Plattform-Serveranwendungen ASP.NET Core .NET Standard 2.0
Your .NET Standard-based Class Library .NET Framework or PCL netstandard.dll mscorlib.dll Type Forwarding mscorlib.dll mscorlib.dll Framework Assemblies https://www.slideshare.net/terrajobst/net-standard-under-the-hood -
Targeting @ Run Time Cross-Plattform-Serveranwendungen ASP.NET Core .NET Standard 2.0
Your .NET Application Framework Assemblies Your .NET Standard-based Class Library netstandard.dll Type Forwarding https://www.slideshare.net/terrajobst/net-standard-under-the-hood -
Platform-specific APIs .NET Standard (mostly) contains APIs that run everywhere
A small subset will throw PlatformNotSupportedException e.g. Registry, Reflection Emit, Windows Identity Cross-Plattform-Serveranwendungen ASP.NET Core .NET Standard Includes documentation, tests and code -
Platform-specific APIs Conditional compilation VS 2017 provides information about type
availability IDE Tool Roslyn Analyzer to find problematic APIs https://github.com/terrajobst/platform-compat Cross-Plattform-Serveranwendungen ASP.NET Core .NET Standard #if NETSTANDARD1_3 || NETSTANDARD1_4 var code = TypeCode.Boolean; #endif -
Summary Simple, yet powerful idea for creating cross-platform-targeting .NET libraries
and applications Good and growing API support No breaking changes between versions .NET Standard 2.0 (Q3 2017) brings compatibility with existing .NET Framework libraries Using platform code could shrink targeting platforms Targeting platform specific APIs could result in an error or conditional compilation Cross-Plattform-Serveranwendungen ASP.NET Core .NET Standard -
Overview .NET Core is an open source implementation of the
.NET Standard specification: https://github.com/dotnet/core Runs on Linux, macOS and Windows CLI tools available Supports C# and F# (VB.NET is coming) Compatible to .NET Framework, Xamarin and Mono (due to .NET Standard) Fully supported by Microsoft (LTS support three years after GA) Cross-Plattform-Serveranwendungen ASP.NET Core .NET Core -
Deployment Offers flexible deployment possibilities included within the app
(self-contained deployments) multiple versions can be installed side-by-side (framework-dependent deployments) can be installed per user or machine-wide Cloud-ready Cross-Plattform-Serveranwendungen ASP.NET Core .NET Core -
Application Models Shipped with .NET Core Console Applications Built
on top of .NET Core ASP.NET Core Windows Universal Platform Xamarin.Forms Cross-Plattform-Serveranwendungen ASP.NET Core .NET Core -
IDEs Cross-Plattform-Serveranwendungen ASP.NET Core .NET Core VS 2017 VS Code
JetBrains Rider VS for Mac -
Use case depending alternatives Node.js JavaScript, TypeScript, CoffeeScript, …
Restify, Express, Koa.js SequelizeJS, ORM Node Package Manager, YARN Java Jersey, RESTful WebServices Hibernate, ORM Maven, Package Management Ruby, Python, … Cross-Plattform-Serveranwendungen ASP.NET Core .NET Core -
Summary .NET Core is an implementation of .NET Standard Runs
cross-platform on Linux, macOS and Windows Can be installed side-by-side Cloud-ready Cross-Plattform-Serveranwendungen ASP.NET Core .NET Core -
Overview Unifies MVC and Web APIs Built-in dependency injection Cloud-ready
configuration system HTTP Request Pipeline Hostable in IIS or as Self Host Everything’s a NuGet Package Leads to having a lot packages installed (“Hello node_modules J”) Built on .NET Core Open Source, https://github.com/aspnet/Home “Can I port my application to .NET Core?” https://icanhasdot.net/ Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core -
Compared to ASP.NET ASP.NET Core Runs on Linux, macOS, Windows
C#, F# MVC & Web API SignalR is in development New platform, new toolings Multiple versions per machine MSDN: “Ultra Performance” ASP.NET Runs on Windows C#, F#, VB.NET MVC, Web API, WebForms, WebPages, SignalR Mature platform One version per machine MSDN: “High Performance” Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core -
Hosting Kestrel: ASP.NET Core’s Web Server IISIntegration to host in
IIS Mandatory for Azure Specifies a class used for Startup configuration Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } -
Startup ConfigureServices: Used for configuring the built-in dependency injection Configure:
Used for configuring the HTTP pipeline via IApplicationBuilder Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core public class Startup { public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { } } -
Dependency Injection Built-in dependency injection Constructor injection should be
preferred over direct DI container access Overriding the container is possible, e.g. to use AutoFac instead Throws an error when a dependency could not be resolved (e.g. wrong container configuration) Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core -
Dependency Injection Supports three lifetimes Transient: Creates an instance
each it is requested Scoped: Creates an instance once per request Singleton: Creates an instance once per application Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core public void ConfigureServices(IServiceCollection services) { services.AddTransient<IIdGenerator, IdGenerator>(); services.AddScoped<ICustomerService, DatabaseCustomerService>(); services.AddSingleton<ICacheService, InMemoryCacheService>(); } -
Pipeline Customizable HTTP pipeline Every request will run through Order
in code defines the order of the pipeline Nesting of pipelines is possible IApplicationBuilder is used to define the pipeline Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware public void Configure(IApplicationBuilder app) { app.UseExceptionHandler("/Home/Error"); app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); } -
Multiple Environments Support multiple environments like Development, Staging or Production
out-of-box Can be set via environment variable ASPNETCORE_ENVIRONMENT Convention based application startup Startup, StartupDevelopment, Startup{Environment} Careful, using webhostBuilder.UseStartup<Startup>() overrides this behavior Configure, ConfigureDevelopment, Configure{Environment} ConfigureServices, ConfigureDevelopmentServices, Configure{Environment}Services Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core -
Multiple Environments IHostingEnvironment for checking environment at runtime Checking within
a Razor View Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment() || env.IsProduction() || env.IsStaging() || env.IsEnvironment(”MyEnv")) { } } <environment names="Development"> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /> </environment> <environment names="Staging,Production"> <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css" /> </environment> -
Configuration System ConfigurationBuilder is used to define configuration sources Order
is used for configuration overriding, later defined sources override previous defined Optional sources and sources depending on the environment are possible Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } -
Authentication Middleware within the pipeline “Plug & Play” solutions for
authentication ASP.NET Identity IdentityServer 4, open source project Different authentication schemes Cookies Bearer Basic External providers Custom Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core -
Controllers Two base classes for controllers ControllerBase: Preferred for
Web APIs, offers everything except Views Controller: Preferred for MVC, inherits from ControllerBase and adds View capabilities Offer various methods for returning a result Ok() / NotFound() / StatusCodeResult() FileResult() / FileContentResult() / FileStreamResult() Offers access to authenticated user via User property Can be asynchronous using async/await pattern If enabled, automatic Content Negotiation Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core -
Views Represent (a piece of) HTML to be rendered in
the browser Uses Razor View Engine Supports strongly typed Views with a ViewModel Can make use of ViewBag, ViewData and Model to transfer data from and to controllers General layout can be applied Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core -
Routing Routing: Mapping URLs to actions (methods within a controller)
Routing via definition in pipeline Routing via attributes Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core public void Configure(IApplicationBuilder app) { app.UseMvc(routes => routes.MapRoute("api", "{controller}/{action}")); } [Route("customers")] public class CustomerApiController : ControllerBase { [HttpGet("{id:int}")] public IActionResult Get(int id) { } } -
Routing Routing via custom routing handler Support for all important
HTTP verbs like GET, POST, PUT, DELETE Routing in Views via Tag Helpers Controller can also be specified Tag Helper asp-route-{parameter} accepts any custom parameter Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core <a asp-action="Delete" asp-route-id="@item.ID">Delete</a> <a asp-controller="Customer" asp-action="Delete" asp-route-id="@item.ID">Delete</a> -
Error Handling Provides a developer exception page with detailed information
about errors Supports error page per status code or custom error pages Supports custom error filter per action, controller or globally Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core public void Configure(IApplicationBuilder app) { // Use in development only app.UseDeveloperExceptionPage(); // Simple status code error pages app.UseStatusCodePages(); // Custom error handler app.UseExceptionHandler("/error"); } -
Swagger Help Pages NuGet: Swashbuckle.AspNetCore Swagger: Generates a swagger.json containing
all information about your Web APIs Swagger UI: Provides a basic UI to view the swagger.json Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info() { Title = "Awesome Customer API", Version = "1.0" }); }); } public void Configure(IApplicationBuilder app) { app.UseSwagger(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("v1/swagger.json", "API v1"); }); } -
Summary Unifies MVC and Web APIs Built-in dependency injection Cloud-ready
HTTP Pipeline & Configuration System Several hosting options Help Pages via Swagger Cross-Plattform-Serveranwendungen ASP.NET Core ASP.NET Core -
Overview Open source implementation: https://github.com/aspnet/EntityFramework Lightweight & cross-platform version of
.NET’s full-fledged EntityFramework Support different database providers MS SQL SQLite Postgres InMemory Offers Commandline Tools Code First, Database First Migrations Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core -
Compared to EntityFramework 6 EntityFramework Core does not offer the
following features, but they are in development Complex value types (without an ID) Spatial data (geography, geometry) Graphical visualization of the model (Model First) Complex LINQ-Queries Many-to-Many without a joining entity Lazy Loading Stored Procedures Data Seeding Full list available at https://docs.microsoft.com/en-us/ef/efcore-and-ef6/features Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core -
NuGet Package & CLI Core Package: Microsoft.EntityFrameworkCore Database Provider Packages
MS SQL: Microsoft.EntityFrameworkCore.SqlServer Postgres: Npgsql.EntityFrameworkCore.PostgreSQL SQLite: Microsoft.EntityFrameworkCore.SQLite CLI Tools Powershell: Microsoft.EntityFrameworkCore.Tools cmd/bash: Microsoft.EntityFrameworkCore.Tools.DotNet Careful: cmd/bash is not installable via NuGet, only by editing .csproj directly Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core -
Model Working with EntityFramework Core is based on a model
A model is a simple class with specific attributes Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core public class CustomerEntity { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } } -
Database Context A database context (DbContext) represents a session to
the database Has one or multiple DbSet<EntityClass> to query the database Allows executing raw SQL queries Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core public class SampleApplicationDbContext : DbContext { public SampleApplicationDbContext(DbContextOptions options) : base(options) { // Overriding constructor is necessary to make use of DbContextOptions } public DbSet<CustomerEntity> Customers { get; set; } } -
Database Context DbContext can be added to the dependency injection
Services can request a DbContext via constructor injection Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core public void ConfigureServices(IServiceCollection services) { services.AddDbContext<SampleApplicationDbContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("SampleApplication")); } ); } public class CustomerService { public CustomerService(SampleApplicationDbContext dbContext) { } } -
Fluent API Instead of using attributes to define a model,
the Fluent API can be used Fluent API has a richer API than the attributes for more complex scenarios Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core public class SampleApplicationDbContext : DbContext { protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<CustomerEntity>() .HasKey(e => e.Id); modelBuilder.Entity<CustomerEntity>() .Property(e => e.FirstName) .IsRequired(); } } -
Querying LINQ for database querying Simple selects Ordering
Grouping Limiting Can load related data Eager Loading Explicitly Lazy Loading is in development Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core public class CustomerService { private readonly SampleApplicationDbContext _dbContext; public CustomerService(SampleApplicationDbContext dbContext) { _dbContext = dbContext; } public ICollection<CustomerEntity> List() { return _dbContext.Customers .OrderBy(c => c.Id) .ToList(); } } -
Saving Tracks changes on entities per default Writes back changes
to the database when the DbContext is saved Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core public void Update() { var entity = _dbContext.Customers.First(); entity.FirstName = "Max"; _dbContext.SaveChanges(); } -
Saving Related data is also saved on change tracked entities
Use AsNoTracking() when querying to not track changes, e.g. for read-only scenarios Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core public ICollection<CustomerEntity> List() { return _dbContext.Customers .AsNoTracking() .ToList(); } -
Transactions SaveChanges() calls done as a transaction by default Custom
transaction can be create by using DbContext.Database.BeginTransaction() Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core using (var transaction = _dbContext.Database.BeginTransaction()) { try { _dbContext.Customers.Add(new CustomerEntity { FirstName = "Max" }); _dbContext.SaveChanges(); _dbContext.Customers.Add(new CustomerEntity { FirstName = "Erika" }); _dbContext.SaveChanges(); transaction.Commit(); } catch (Exception e) { // TODO: Handle exception } } -
Migrations Needs the PowerShell or cmd/bash tools installed Add Migrations
via PowerShell: Add-Migration MigrationName cmd/bash: dotnet ef migrations add MigrationName Custom database initializer is needed to actually apply the migrations on startup Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core public class DatabaseInitializer { public void Migrate() { _dbContext.Database.Migrate(); } } -
Summary Cross-platform version of .NET’s EntityFramework Not all features are
supported yet Offers PowerShell and cmd/bash toolings Supports transactions & migrations Support multiple database providers and an InMemory database for testing Cross-Plattform-Serveranwendungen ASP.NET Core EntityFramework Core -
Summary .NET Standard makes it easier to create multi-targeting code
(replacing PCLs) .NET Standard 2.0 can target existing .NET code to reuse your existing business logic ASP.NET Core provides a cross-platform possibility for MVC & Web APIs ASP.NET Core is cloud-ready and offers a customizable HTTP pipeline EntityFramework Core provides cross-platform and cross-database capabilities Cross-Plattform-Serveranwendungen ASP.NET Core .NET Core & ASP.NET Core & EntityFramework Core -
.NET Standard MSDN https://docs.microsoft.com/en-us/dotnet/articles/standard/library Introducing .NET Standard https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/ .NET Core
MSDN https://docs.microsoft.com/en-us/dotnet/articles/core/ ASP.NET Core MVC MSDN https://docs.microsoft.com/en-us/aspnet/core/mvc/overview ASP.NET Core Web API MSDN https://docs.microsoft.com/en-us/aspnet/core/mvc/web-api/ EntityFramework Core MSDN https://docs.microsoft.com/en-us/ef/ Cross-Plattform-Serveranwendungen ASP.NET Core Resources -
Modern & Pragmatisch Christian Weyer May the 4th 2017 @
2 PM Mythos Microservices & wie diese in der .NET-Welt funktionieren Cross-Plattform-Serveranwendungen ASP.NET Core Microservices-Architekturen .NET/.NET Core