【原生態跨平臺:ASP.NET Core 1.0(非Mono)在 Ubuntu 14.04 服務器上一對一的配置實現-篇幅1】

-----------------2017年了 下面的都是老版本的了.無語ing------------------------javascript

asp.net core 正處於快速成長期,按照官方的路線,2017年的 第三個季度,大概就是10月份了。2.0正式版 面世。估計那時候就能夠愉快的玩耍了。。。。。。php

Release Time frame*
2.0-preview1 Q2 2017
2.0-preview2 Q2 2017
2.0 Q3 2017
2.1 Q4 2017

Release Time frame*

css

 最坑莫過於 project.json  呵呵 。。。。。。。。。。。。。。。。。。。。。html

最新的 請看java

Set up a hosting environment for ASP.NET Core on Linux with Nginx, and deploy to it

Ubuntu 14.04 的

【asp.net core】Publish to a Linux-Ubuntu 14.04 Server Production Environment

Publish to a Linux Production Environmentnode

 

 

--------------------------------------------------mysql

 

雞凍人心的2016,微軟高產年。linux

build 2016後 各類乾貨層出不窮。ios

1 Win10 集成了bash  ,實現了納德拉的成諾,Microsoft Love Linux!!!nginx

2 跨平臺  ,收購Xamarin 。。還給開源了

3 Sqlserver有了Linux的版本...............

4 ASP.NET 5迎來第一個穩定版本,跨平臺。在Windows Linux Mac OsX 中都能玩了.........

光說不練假把式,先上圖一枚....

-------------------------省略圖了,博客園上傳圖片失敗,又粗問題了--------------------------

 

那各位,咱只能文字版本了。。。。

 在借鑑了行內無數的博文後,決定嘗試下。然而,隨着前期,微軟的asp.net core不斷升級。。之前的基於Beta版本的  預覽版本的博文可能都再也不好用了。。

環境:Ubuntu 14.04 服務器版

虛擬機:Vmware 10

工具 :XShell

開發工具:VS2015企業版+ASP.NET Update1

反向代理:Nginx

是否用到了Docker?沒,牆過高了,鏡像拉不過來,秒懂!???!?!?!

 

 

Let us go!

 

 

Installing on Ubuntu 14.04

The following instructions were tested using Ubuntu 14.04. Other versions of Ubuntu and other Debian based distros are unlikely to work correctly.

去ubuntu官網下載此版本。微軟號稱1.0的Core  僅僅這個版本的Linux穩定。其餘的,對不起,祝福你。。

下載地址:

http://releases.ubuntu.com/14.04/

完過後,建立虛擬機。。。

 

開始在Linux下 安裝 ASP.NET Core

 

Install the .NET Version Manager (DNVM)
Use the .NET Version Manager (DNVM) to install different versions of the .NET Execution Environment (DNX) on Linux.

Install unzip and curl if you don’t already have them:

 

#安裝過程當中須要的工具

sudo apt-get install unzip curl

 


Download and install DNVM:

 

 

#安裝DNVM  版本管理器

curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | DNX_BRANCH=dev sh && source ~/.dnx/dnvm/dnvm.sh

 

 


Once this step is complete you should be able to run dnvm and see some help text.

Install the .NET Execution Environment (DNX)
The .NET Execution Environment (DNX) is used to build and run .NET projects. Use DNVM to install DNX for Mono or .NET Core (see Choosing the Right .NET For You on the Server).

To install DNX for .NET Core:

Install the DNX prerequisites:

#安裝DNX須要的工具

sudo apt-get install libunwind8 gettext libssl-dev libcurl4-openssl-dev zlib1g libicu-dev uuid-dev

 


Use DNVM to install DNX for .NET Core:

#安裝最新版本的 DNX(如今是 1.0的update 2)

dnvm upgrade -r coreclr

 

#安裝完畢後。執行下面的命令 ,查看dnx的安裝目錄。很重要哦,這是運行時。

which dnx

 

 ---------------------------完過後呢,開始搭建HTTP Server-----------------

內置的爲 Kestrel,基於 Libuv。

安裝 libuv

#!/usr/bin/env bash
sudo apt-get install make automake libtool curl
curl -sSL https://github.com/libuv/libuv/archive/v1.8.0.tar.gz | sudo tar zxfv - -C /usr/local/src
cd /usr/local/src/libuv-1.8.0
sudo sh autogen.sh
sudo ./configure
sudo make
sudo make install
sudo rm -rf /usr/local/src/libuv-1.8.0 && cd ~/
sudo ldconfig

 

 -------------------------------好了,安裝基本的ASP.NET CORE 1.0環境完畢了------------------------------

安裝VS2015
安裝最新發布的 asp.net 5更新補丁
建立web

發佈到 ubuntu

 

#bash 命令 進入src/Your ProjetcName 目錄,還原程序須要的依賴的組件包。組件包 都發布在微軟的Nuget上。

#看看都有啥 https://www.myget.org/gallery/aspnetvnext


dnu restore
dnx web

***********注意上面的 web節點。。這個是在project.json中的commands節點。。************(若是不給 --server參數  默認就是 kestrel,默認端口是5000)

示範端口:(在RC2中 Kestrel 不能僅僅是用名稱Kestrel,須要是全名!!!!!!!)
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel --server.urls http://*:5004",
"kestrel": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5004",
"ef": "EntityFramework.Commands"
},

這裏有個釘子哦。。。。

-----localhost僅僅是本機訪問的綁定,不能在本機外訪問(是用Nginx 反向代理除外,稍後講)
*:port 進行機器iP的綁定端口

------------------------------------------------------------------------

#好了,當執行了 dnx [node name ] 指令後,就能夠訪問站點了。

curl http://localhost:5000

 

#查看 dnx  是否運行中

ps -el|grep dnx

 

------------web  程序已經啓動了,咋地管理呢?---------------

1 更新

2 暫停

3 啓動

1 更新,只要更改了project.json文件,程序就自動更新了。

2 暫停 重啓

dnx 沒有對應的重啓 Kestrel的命令...........
#若是出現端口占用重複的問題,那麼直接殺死 dnx 監聽的進程便可。。。。。
lsof -i :5004
kill -9 portnumber

 

重啓是個麻煩事,每次都要進程序目錄,有簡單的方法嗎,有!!!!!!一下子講Linux下的進程守護軟件   supervisor !

 有人說了,DD的,無法進行機器IP的訪問啊!!!!

彆着急呵呵呵呵~~~~~~~~~~~~防火牆你懂的。。。。

 


防火牆 打開對應的端口訪問

sudo ufw allow 5000/tcp

-------------------------防火牆篇----------------

二、啓用:

ufw enable

ufw default deny

三、開啓/禁用:

ufw allow 22/tcp 容許全部的外部IP訪問本機的22/tcp (ssh)端口

ufw deny 22/tcp 禁止全部外部IP訪問本機的22/tcp(ssh)端口

ufw delete deny 22/tcp 刪除防火牆中的規則


有時候關閉軟件後,後臺進程死掉,致使端口被佔用。下面以JBoss端口8083被佔用爲例,列出詳細解決過程。

解決方法:

1.查找被佔用的端口

netstat -tln 
netstat -tln | grep 8083 
netstat -tln 查看端口使用狀況,而netstat -tln | grep 8083 則是隻查看端口8083的使用狀況

 

2.查看端口屬於哪一個程序?端口被哪一個進程佔用

lsof -i :8083 

3.殺掉佔用端口的進程

kill -9 進程id

----------------------------------------

 

 

如今  是否是能機器IP + 端口的方式訪問了?

好,咱們開始說Nginx作反向代理。

等等  不是有了HTTP SERVER了??那個Kestrel ,確實是個Server 可是管理太麻煩啦,並且有些現有的模塊,它都沒有,so ,來吧,Nginx !!

Apache也行,大家本身找配置。。。。

 

 

#開始安裝 Nginx

sudo apt-get install nginx

從新啓動nginx:
sudo service nginx stop
sudo service nginx start
或者
sudo nginx -s reload
sudo service nginx restart


sudo ufw allow 80/tcp

 

 

Nginx is used as a reverse proxy for static contents in general and you can also enable gzip compression on your dynamic content. Kestrel doesn't have this feature.

Personally, I don't use Kestrel on Linux but firefly which is a managed HTTP server. I also wrote a fastCGI server for ASP.NET 5 but firefly is the best in the realm of performance.


sudo apt-get install nginx

 #配置反向代理

vi /etc/nginx/sites-available/default

#try_files $uri $uri/ =404;-----------必定要註釋掉這個配置節點 。咱們的asp.net mvc是基於路由訪問控制 而不是經過CGI文件(asp php py等)

server { listen 80; location / { proxy_pass http:http://*:5000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade;  proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }


proxy_pass http://*:5004;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;







接下來 就是nginx的配置了。。壓縮 頭信息 緩存 等等


nginx的配置是門藝術,大家懂的。。。我再也不獻醜了呵呵呵呵。


好了,機器IP 的80端口 也給它開放出來。而後,就機器IP在外部訪問就好。

 

---------------------------------好,咱們說說  Kestrel的 暫停 重啓問題吧 呵呵呵呵---------------------------


自動啓動Web
Monitoring our Web Application

Nginx will forward requests to your Kestrel server, however unlike IIS on Windows, it does not mangage your Kestrel process. In this tutorial, we will use supervisor to start our application on system boot and restart our process in the event of a failure.

Installing supervisor

#首先安裝 supervisor ,進程守護

sudo apt-get install supervisor

 

To have supervisor monitor our application, we will add a file to the

#進入
cd /etc/supervisor/conf.d/ 

#建立 配置文件 kestrel_default.conf

 

[program:kestrel_default]
command=su -c "/root/.dnx/runtimes/dnx-coreclr-linux-x64.1.0.0-rc1-update2/bin/dnx web --server.urls=http://*:5004" root
directory=/home/www/test/src/BookStore/
autorestart=true
autostart=true
#stdout_logfile=/home/rodolfo/WebApplicationBasic/logs/app_std_out.log
#stderr_logfile=/home/rodolfo/WebApplicationBasic/app_err.log

******注意上面的,directory command 節點很重要。機器重啓後,自動在指定的目錄,執行對應的指令。 好吧,千萬記得查詢下,你的dnx的安裝路徑。

這個路徑不是固定的,我是用的root用戶登陸的,而後給我安裝到了這個地方。。。。。。。。。

*********

#配置完畢後,刷新supervisor的配置加載信息

 

sudo supervisorctl reread
sudo supervisorctl update
 
 
#開始對配置的集成進行管理
#Listar os processos configurados e o status
sudo supervisorctl
 
#Parar um processo
sudo supervisorctl stop kestrel_default
 
#iniciar um processo
sudo supervisorctl start kestrel_default
 
 

 

#大招是直接把 supervisor 停了,你懂的。
Once you are done editing the configuration file, restart the supervisord process to change the set of programs controlled by supervisord.

sudo service supervisor stop
sudo service supervisor start

 ----------------------------------嗯,基本一個完整的Web項目配置  管理完事了,性能還行,如何優化等,那是另外一說了-----------------

至於鏡像容器 Docker。。。。。嗯,我是沒弄成功,大家本身搞,好像有弄成功的,我這邊的訪問不了官網的源,未能解析host ,我一看就知道啥意思 呵呵

各位好運。。。。。。

 

(完!)

 

順便說一下,進程守護 能夠監聽多個ASP.NET CORE 程序,配置方案:

[program:kestrel_default]
command=su -c "/home/rodolfo/.dnx/runtimes/dnx-coreclr-linux-x64.1.0.0-rc1-update1/bin/dnx web --server.urls=http://0.0.0.0:5001" rodolfo
directory=/home/rodolfo/WebApplicationBasic
autorestart=true
autostart=true
stdout_logfile=/home/rodolfo/WebApplicationBasic/logs/app_std_out.log
stderr_logfile=/home/rodolfo/WebApplicationBasic/app_err.log
 
[program:kestrel_default1]
command=su -c "/home/rodolfo/.dnx/runtimes/dnx-coreclr-linux-x64.1.0.0-rc1-update1/bin/dnx web --server.urls=http://0.0.0.0:5002" rodolfo
directory=/home/rodolfo/WebApplicationBasic
autorestart=true
autostart=true
stdout_logfile=/home/rodolfo/WebApplicationBasic/logs/app_std_out2.log
stderr_logfile=/home/rodolfo/WebApplicationBasic/app_err2.log
 
[program:kestrel_default2]
command=su -c "/home/rodolfo/.dnx/runtimes/dnx-coreclr-linux-x64.1.0.0-rc1-update1/bin/dnx web --server.urls=http://0.0.0.0:5003" rodolfo
directory=/home/rodolfo/WebApplicationBasic
autorestart=true
autostart=true
stdout_logfile=/home/rodolfo/WebApplicationBasic/logs/app_std_out3.log
stderr_logfile=/home/rodolfo/WebApplicationBasic/app_err3.log
 
[program:kestrel_default3]
command=su -c "/home/rodolfo/.dnx/runtimes/dnx-coreclr-linux-x64.1.0.0-rc1-update1/bin/dnx web --server.urls=http://0.0.0.0:5004" rodolfo
directory=/home/rodolfo/WebApplicationBasic
autorestart=true
autostart=true
stdout_logfile=/home/rodolfo/WebApplicationBasic/logs/app_std_out4.log
stderr_logfile=/home/rodolfo/WebApplicationBasic/app_err4.log

 

記住,玩Linux的命令語法,bash 的Shell命令查詢去我前面的文章找。 離線 chm 你懂的。。哈哈 祝福各位。

 

 

附帶資料索引:

Bookmarks

Bookmarks

書籤欄

ASP.NET Cross

http://dotnet.github.io/

 


Microsoft Loves Linux | Windows Server Blog
Why Microsoft loves Linux | ZDNet
讓咱們 Core 在一塊兒:ASP.NET Core & .NET Core - 開源中國社區
Project.json file · aspnet/Home Wiki · GitHub
Jexus 網站服務器和 ASP.NET 跨平臺開發 – Half-Blood Programmer
Jexus 網站服務器和 ASP.NET 跨平臺開發 - 小斌斌 - 博客園
Jexus Web Server - Home
ASP.NET跨平臺從這裏開始!
ASP.NET Core 1.0 入門——瞭解一個空項目 - 勤奮的小孩 - 博客園
驚鴻哥的港灣
Gallery - MyGet - Hosting your NuGet, Npm, Bower and Vsix packages
Get ASP.NET
Running ASPNET 5 and .NET Core on Linux - CodeProject
Using Docker ENV with ASP.NET 5 | .NET Liberty
ASP.NET 5 (vNext) Linux部署 - Charlie.Zheng - 博客園
Getting started with ASP.NET 5 and Docker | http://luukmoret.github.io
Shayne Boyer: Legion of Heroes: haproxy, nginx, Angular 2, ASP.NET Core, Redis and Docker
Deploy an ASP.NET Core app to a Docker container using Release Management
NGINX Reverse Proxy and Load Balancing for ASP.NET 5 Applications with Docker Compose - Tugberk Ugurlu's Blog
aguacongas (Olivier Lefebvre) · GitHub
Fun with ASP.NET 5, Linux & Docker, Part 3
ASP.NET 5 in Docker on Linux
Publish to a Linux Production Environment — ASP.NET documentation
Docker Dockerfile詳解 - edwardsbean的專欄 - 博客頻道 - CSDN.NET
經常使用docker命令,及一些坑 - edwardsbean的專欄 - 博客頻道 - CSDN.NET
DOCKER windows 7 詳細安裝教程 - 初夏的專欄 - 博客頻道 - CSDN.NET
Developing ASP.NET Apps in Docker Containers | Steve Lasker's Web Log – www.SteveLasker.com/Blog


個人隨筆 - 博客後臺 - 博客園

JS


Javascript的10個設計缺陷 - 阮一峯的網絡日誌
深刻理解javascript原型和閉包(完結) - 王福朋 - 博客園
Playground · TypeScript

 

 

 


Why not using ASP.NET 5 default web server, Kestrel?

Managing ASP.NET 5 web applications with Kestrel isn’t easy, or isn’t as easy as managing virtual hosts
like Apache or Nginx. Each web application must be running on one process of the Kestrel web server.
It means that we can’t run two web applications on the same port. Also, unlike Apache or Nginx, we cannot
declare our web applications in configuration files, and launch them all with a single command. We have
to run 「dnx web」 in a terminal for every web application! What about HTTPS? Well, I’ve saw a Nuget package
for a HTTPS Kestrel version, but it doesn’t look like as easy to configure as the other popular web servers.

Like I said before, I really like Nginx. Nginx is very good for serving static files and passing other
requests to other web servers (reverse proxying), and in our case, Kestrel.

Installation

I’m assuming that you already have a .NET environment installed on your Linux distribution. If not,
follow the official documentation to install it: DNVM, the .NET version manager, and the .NET Core
DNX runtime. At this time, the RC2 of .NET Core isn’t working for me, so I’m using the RC1.

Nginx configuration

Now let’s create a nginx configuration for our web application. We are going to proxy every request
to the Kestrel web server except the assets such as Javascript, CSS, images and other static files.
Nginx is the best for serving static content. We are going to add a HTTP header to be sur that it’s
Nginx that served our static content and not Kestrel.

server {
# Port and domain
listen 80;
server_name aspnet.local;

# Path to the wwwroot folder
root /home/developer/projects/WebApplicationBasic/wwwroot;

# Static content
location ~ \.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm|woff2|svg)$ {
expires 1d;
access_log off;
add_header X-Static-File true;
}

# Pass requests to Kestrel
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Connection "";
proxy_http_version 1.1;
}
}
The 19th and 20th lines are very important. It covers a bug found in the RC1 version of Kestrel.
If you don’t add them, your browser will wait for an answer forever even if the server has sent
the response. Have a look here to find more information about this bug.

 

Adding MySQL to an ASP.NET 5 project, using Visual Studio Code? This might help.

I’ve been working on learning ASP.NET 5 the last few weeks.  I like it.  It feels like a solid platform, and I especially like Visual Studio Code.  I’m discovering a few quirks, though, as is common when you’re learning a new thing.  This one in particular, how to add the MySQL connector to a project, I wanted to share the solution I found.

If you were using Visual Studio proper, it’d be straightforward to use the 「manage packages」 dialog to find and add the MySQL connector.  Visual Studio Code, however, doesn’t provide that dialog.  The way you can add MySQL, then, is by opening up project.json and finding the 「dependencies」 block.  Add a line for MySQL:

"dependencies": {
  ...
  "MySql.Data": "6.9.8"
},

And then scroll down and find the 「frameworks」 block.  I removed the entry for 「dnxcore50」 and set up the entry for 「dnx451」 like so:

"frameworks": {
  "dnx451":  {
    "frameworkAssemblies": {
      "System.Data": "4.0.0.0"
    }
  }
},

You’ll want to be sure to rerun dnu restore as needed.  After that, your new MySqlConnection(); and dbh.Open(); statements should work as normal.

Hope this helps,

Steve

 

 

 

Blog

Using Entity Framework 6 and MySQL on ASP.NET 5 (vNext)

Visual Studio 2015 was recently released, and with it came a newer beta of ASP.NET 5 (formerly referred to as "ASP.NET vNext"). ASP.NET 5 is a complete rewrite of ASP.NET, focusing on being lightweight, composible, and cross-platform. It also includes an alpha version of Entity Framework 7. However, EF7 is not yet production-ready and does not support all features of EF6. One feature that is missing from EF6 is support for other database providers - Only SQL Server and SQLite are supported at this time.

 

I wanted to transition a site over to ASP.NET 5, but needed to continue using MySQL as a data source. This meant getting Entity Framework 6 running on ASP.NET 5, which is pretty much undocumented right now. All the documentation and tutorials for EF6 heavily relies on configuration in Web.config, which no longer exists in ASP.NET 5. In this post I'll discuss the steps I needed to take to get it running. An example project containing all the code in this post can be found at  https://github.com/Daniel15/EFExample.

 

Since EF6 does not support .NET Core, we need to remove .NET Core support (delete "dnxcore50": { } from project.json). Once that's done, install the EntityFramework and MySql.Data.Entity packages, and add references to System.Data and System.Configuration. For this post, I'll be using this basic model and DbContext, and assume you've already created your database in MySQL:

1
2
3
4
5
6
7
8
9
10
11
12
public class MyContext : DbContext
{
     public virtual DbSet<Post> Posts { get ; set ; }
}
  
public class Post
{
     public int Id { get ; set ; }
     public string Title { get ; set ; }
     public string Content { get ; set ; }
}

Entity Framework 6 relies on the provider and connection string being configured in Web.config. Since Web.config is no longer used with ASP.NET 5, we need to use code-based configuration to configure it instead. To do so, create a new class that inherits fromDbConfiguration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class MyDbConfiguration : DbConfiguration
{
     public MyDbConfiguration()
     {
         // Attempt to register ADO.NET provider
         try {
             var dataSet = (DataSet)ConfigurationManager.GetSection( "system.data" );
             dataSet.Tables[0].Rows.Add(
                 "MySQL Data Provider" ,
                 ".Net Framework Data Provider for MySQL" ,
                 "MySql.Data.MySqlClient" ,
                 typeof (MySqlClientFactory).AssemblyQualifiedName
             );
         }
         catch (ConstraintException)
         {
             // MySQL provider is already installed, just ignore the exception
         }
  
         // Register Entity Framework provider
         SetProviderServices( "MySql.Data.MySqlClient" , new MySqlProviderServices());
         SetDefaultConnectionFactory( new MySqlConnectionFactory());
     }
}

The first part of the configuration is a hack to register the ADO.NET provider at runtime, by dynamically adding a new configuration entry to the system.data section. The second part registers the Entity Framework provider. We also need to modify the configuration file to include the connection string. You can use any configuration provider supported by ASP.NET 5, I'm using config.json here because it's the default provider.

1
2
3
4
5
6
7
8
{
   "Data" : {
     "DefaultConnection" : {
       "ConnectionString" : "Server=localhost; Database=test; Uid=vmdev; Pwd=password;"
     }
   }
}

 

Now that we have the configuration, we need to modify the context to use it:

1
2
3
4
5
6
7
8
9
10
[DbConfigurationType( typeof (MyDbConfiguration))]
public class MyContext : DbContext
{
     public MyContext(IConfiguration config)
         : base (config.Get( "Data:DefaultConnection:ConnectionString" ))
     {
     }
     // ...
}

An instance of IConfiguration will be automatically passed in by ASP.NET 5's dependency injection system. The final step is to registerMyContext in the dependency injection container, which is done in your Startup.cs file:

1
2
3
4
5
6
public void ConfigureServices(IServiceCollection services)
{
     // ...
     services.AddScoped<MyContext>();
}

AddScoped specifies that one context should be created per request, and the context will automatically be disposed once the request ends. Now that all the configuration is complete, we can use MyContext like we normally would:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class HomeController : Controller
{
     private readonly MyContext _context;
  
     public HomeController(MyContext context)
     {
         _context = context;
     }
  
     public IActionResult Index()
     {
         return View(_context.Posts);
     }
}

Hope you find this useful!

Until next time, 
— Daniel

 

 

Using EF6 with ASP.NET MVC Core 1.0 (aka MVC 6)

This week Microsoft announced that it is renaming ASP.NET 5 to ASP.NET Core 1.0.  In general I think this is a very good step.  Incrementing the version number from 4 to 5 for ASP.NET gave the impression that ASP.NET 5 was a continuation of the prior version and that a clean migration path would exist for upgrading apps from ASP.NET 4 to 5.  However, this did not reflect the reality that ASP.NET 5 was a completely different animal, re-written from the ground up, and that is has little to do architecturally with its predecessor.  I would even go so far as to say it has more in common with node.js than with ASP.NET 4.

You can download the code for this post from my Demo.AspNetCore.EF6 repository on GitHub.

Entity Framework 7, however, has even less in common with its predecessor than does MVC, making it difficult for developers to figure out whether and when they might wish to make the move to the new data platform.  In fact, EF Core 1.0 is still a work in progress and won’t reach real maturity until well after initial RTM.  So I’m especially happy that EF 7 has been renamed EF Core 1.0, and also that MVC 6 is now named MVC Core 1.0.

The problem I have with the name ASP.NET Core is that it implies some equivalency with .NET Core.  But as you see from the diagram below, ASP.NET Core will not only runcross-platform on .NET Core, but you can also target Windows with .NET Framework 4.6.

aspnetcore-mvc-ef.png

Note: This diagram has been updated to reflect that EF Core 1.0 (aka EF 7) is part of ASP.NET Core 1.0 and can target either .NET 4.6 or .NET Core.

It is extremely important to make this distinction, because there are scenarios in which you would like to take advantage of the capabilities of ASP.NET Core, but you’ll need to run on .NET 4.6 in order to make use of libraries that are not available on .NET Core 1.0.

So why would you want to use ASP.NET Core 1.0 and target .NET 4.6?

As I wrote in my last post, WCF Is Dead and Web API Is Dying – Long Live MVC 6, you should avoid using WCF for greenfield web services, because: 1) is it not friendly to dependency injection, 2) it is overly complicated and difficult to use properly, 3) it was designed primarily for use with SOAP (which has fallen out of favor), and 4) because Microsoft appears to not be investing further in WCF.  I also mentioned you should avoid ASP.NET Web API because it has an outdated request pipeline, which does not allow you to apply cross-cutting concerns, such as logging or security, across multiple downstream web frameworks (Web API, MVC, Nancy, etc).  OWIN and Katana were introduced in order to correct this deficiency, but those should be viewed as temporary remedies prior to the release of ASP.NET Core 1.0, which has the same pipeline model as OWIN.

The other important advantage of ASP.NET Core is that it completely decouples you from WCF, IIS and System.Web.dll.  It was kind of a dirty secret that under the covers ASP.NET Web API used WCF for self-hosting, and you would have to configure the WCF binding if you wanted implement things like transport security.  ASP.NET Core has a more flexible hosting model that has no dependence on WCF or System.Web.dll (which carries significant per-request overhead), whether you choose to host in IIS on Windows, or cross-platform in Kestrel on Windows, Mac or Linux.

A good example of why you would want to use ASP.NET Core 1.0 to target .NET 4.6 would be the ability to use Entity Framework 6.x.  The first release of EF Core, for example, won’t include TPC inheritance or M-M relations without extra entities.  As Rowan Miller, a program manager on the EF team, stated:

We won’t be pushing EF7 as the ‘go-to release’ for all platforms at the time of the initial release to support ASP.NET 5. EF7 will be the default data stack for ASP.NET 5 applications, but we will not recommend it as an alternative to EF6 in other applications until we have more functionality implemented.

This means if you are building greenfield web services, but still require the full capabilities of EF 6.x, you’ll want to use ASP.NET MVC Core 1.0 (aka MVC 6) to create Web API’s which depend on .NET 4.6 (by specifying 「dnx451」 in the project.json file).  This will allow you to add a dependency for the 「EntityFramework」 NuGet package version 「6.1.3-*」.  The main difference is that you’ll probably put your database connection string in an*.json file rather than a web.config file, or you may specify it as an environment variable or retrieve it from a secrets store.  An appsettings.json file, for example, might contain a connection string for a local database file.

1
2
3
4
5
6
7
{
   "Data" : {
     "SampleDb" : {
       "ConnectionString" : "Data Source=(localdb)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\SampleDb.mdf;Integrated Security=True; MultipleActiveResultSets=True"
     }
   }
}

You can then register your DbContext-derived class with the dependency injection system of ASP.NET Core.

1
2
3
4
5
6
7
8
9
10
11
12
public void ConfigureServices(IServiceCollection services)
{
     // Add DbContext
     services.AddScoped(provider =&gt;
     {
         var connectionString = Configuration[ "Data:SampleDb:ConnectionString" ];
         return new SampleDbContext(connectionString);
     });
 
     // Add framework services.
     services.AddMvc();
}

This will allow you to inject a SampleDbContext into the constructor of any controller in your app.

1
2
3
4
5
6
7
8
9
[Route( "api/[controller]" )]
public class ProductsController : Controller
{
     private readonly SampleDbContext _dbContext;
 
     public ProductsController(SampleDbContext dbContext)
     {
         _dbContext = dbContext;
     }

Lastly, you’ll need to provide some information to EF regarding the provider you’re using (for example, SQL Server, Oracle, MySQL, etc).  In a traditional ASP.NET 4.6 app you would have done that in app.config or web.config.  But in ASP.NET Core you’ll want to specify the provider in a class that inherits from DbConfiguration.

1
2
3
4
5
6
7
public class DbConfig : DbConfiguration
{
     public DbConfig()
     {
         SetProviderServices( "System.Data.SqlClient" , SqlProviderServices.Instance);
     }
}

Then you can apply a DbConfigurationType attribute to your DbContext-derived class, so that EF can wire it all together.

1
2
3
4
5
6
7
8
[DbConfigurationType( typeof (DbConfig))]
public class SampleDbContext : DbContext
{
     public SampleDbContext( string connectionName) :
         base (connectionName) { }
 
     public DbSet Products { get ; set ; }
}

You can download the code for this post from my Demo.AspNetCore.EF6 repository on GitHub.

The primary limitation of targeting .NET 4.6 with EF 6 is that you’ll only be able to deploy your web services on Windows.  The good news, however, is that you’ll be in a great position to migrate from EF 6 to EF Core 1.0 (aka EF 7) as soon as it matures enough to meet your needs.  That’s because the API’s for EF Core are designed to be similar to EF 6.  Then when you do move to EF Core, you’ll be able to use Docker to deploy your web services on Linux VM’s running in a Cloud service such as Amazon EC2, Google Compute Engine, or Microsoft Azure.

相關文章
相關標籤/搜索