using Autofac;
using Autofac.Integration.Mvc;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Infrastructure.Interception;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using WebApplication3.Models; namespace WebApplication3
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{ var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.Register<UserContext>((_) => new UserContext());
builder.Register<IDbInterceptor>((_) => new MyNLogInterceptor()); builder.Register<Func<IDbExecutionStrategy>>((_) => () => new SqlAzureExecutionStrategy());
builder.Register<Func<TransactionHandler>>((_) => () => new CommitFailureHandler()); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //添加一个依赖关系解析
DbConfiguration.Loaded += (s, e) =>
e.AddDependencyResolver(new MyAutofacDependencyResolver(container), overrideConfigFile: false); AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
} public class MyNLogInterceptor : IDbCommandInterceptor
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
} public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
LogCommandComplete(command, interceptionContext);
} public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
} public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
LogCommandComplete(command, interceptionContext);
} public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
} public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
LogCommandComplete(command, interceptionContext);
} private void LogCommandComplete<TResult>(DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
{
if (interceptionContext.Exception == null)
{
logger.Trace("Command completed with result {0}", interceptionContext.Result);
logger.Trace(command.CommandText);
}
else
{
logger.WarnException("Command failed", interceptionContext.Exception);
logger.Trace(command.CommandText);
}
}
} public class MyAutofacDependencyResolver : IDbDependencyResolver
{
private ILifetimeScope container; public MyAutofacDependencyResolver(ILifetimeScope container)
{
this.container = container;
} public object GetService(Type type, object key)
{
if (container.IsRegistered(type))
{
return container.Resolve(type);
} return null;
} public IEnumerable<object> GetServices(Type type, object key)
{
if (container.IsRegistered(type))
{
return new object[] { container.Resolve(type) };
} return Enumerable.Empty<object>();
}
}
}

builder.Register<Func<IDbExecutionStrategy>>((_) => () => new SqlAzureExecutionStrategy());:使用SsqlAzure 执行策略
    builder.Register<Func<TransactionHandler>>((_) => () => new CommitFailureHandler());:注册一个事物处理程序


 使用指定的依赖关系解析程序接口,为依赖关系解析程序提供一个注册点,给MVC提供依赖关系解析。
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

   

 添加一个依赖关系解析,为EF提供依赖关系解析
DbConfiguration.Loaded += (s, e) =>
e.AddDependencyResolver(new MyAutofacDependencyResolver(container), overrideConfigFile: false);
 MyNLogInterceptor:它可以侦听EF发送到数据库的命令
 private void LogCommandComplete<TResult>(DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
{
if (interceptionContext.Exception == null)
{
成功记录日志,命令和完成结果
logger.Trace("Command completed with result {0}", interceptionContext.Result);
logger.Trace(command.CommandText);
}
else
{ 失败记录日志,命令和异常
logger.WarnException("Command failed", interceptionContext.Exception);
logger.Trace(command.CommandText);
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication3.Models; namespace WebApplication3.Controllers
{
public class HomeController : Controller
{
public UserContext Ucontext;
public HomeController(UserContext context)
{
this.Ucontext = context;
}
// GET: Home
public ActionResult Index()
{
User user = new User { Name = "", Pwd = "" };
Ucontext.Users.Add(user); Ucontext.SaveChanges(); return Content("Yes");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Ucontext.Dispose();
}
base.Dispose(disposing);
}
}
}

释放资源

 protected override void Dispose(bool disposing)
{
if (disposing)
{
Ucontext.Dispose();
}
base.Dispose(disposing);
}

实现依赖解析 和  日志记录  还要引入两个包。

1.NLog 2.Autofac


引入Nlog包之后到开Nlog.config取消注释,运行程序之后点击显示所有文件
将会出现一个Logs的文件,日志就在里面。 当我运行程序之后,成功创建了数据。


  日志文件

返回受影响行数一行,因为我只插入了一行吗。
希望你能从中获益:)

EF 连接到 Azure-SQL的更多相关文章

  1. SQL Server ->> 使用Azure Active Directory Authentication连接到Azure SQL Database

    SQL Server 2016以后支持Azure AD集成验证,这当中有些数据驱动必须在高版本才可以使用,支持的包括sqlcmd,SSDT,JDBC,ODBC,SSMS等. 对于SSIS来讲,我们需要 ...

  2. 在 Azure 上创建和链接 Azure SQL 数据库

    本快速入门介绍了如何在 Azure 门户中创建并连接 Azure SQL 数据库.在本教程中完成的所有操作均符合 1 元试用条件. 开始之前 如果您还没有 Azure 账户,可以申请 1 元试用账户. ...

  3. 【数据库-Azure SQL Database】如何创建事务复制将本地数据同步到 SQL Azure

    Azure SQL DB 可以被配置成为 SQL Server 事务复制的一个订阅者( subscriber ). 主要应用场景有两种: 将您的数据迁移到 Azure SQL DB, 并且没有宕机时间 ...

  4. 连接到 Azure 上的 SQL Server 虚拟机(经典部署)

    概述 本主题介绍如何连接到运行于 Azure 虚拟机的 SQL Server 实例. 它介绍了一些常规连接方案,并提供了在 Azure VM 中配置 SQL Server 连接的详细步骤. Impor ...

  5. 使用SSMS 2014将本地数据库迁移到Azure SQL Database

    使用SQL Server Management Studio 2014将本地数据库迁移到Azure SQL Database的过程比较简单,在SSMS2014中,有一个任务选项为“将数据库部署到Win ...

  6. Java连接Azure SQL Database

    Azure SQL Database是Azure上的数据库PAAS服务,让用户可以快速的创建和使用SQL数据库而不用担心底层的备份,安全,运维,恢复等繁琐的工作,本文简单介绍如何使用Java程序连接到 ...

  7. Azure SQL Database (22) Azure SQL Database支持中文值

    <Windows Azure Platform 系列文章目录> 在笔者之前的文章里,已经介绍了如何使Azure SQL Database支持中文: SQL Azure(七) 在SQL Az ...

  8. 如何將 MySQL 資料庫轉移到 Microsoft SQL Server 與 Azure SQL Database

    MySQL 是相當常用之資料庫伺服器,而微軟雲端服務 Microsoft Azure 上 Azure SQL Database 是一個功能強大且經濟實惠的選擇,透過本篇文章,使用 SQL Server ...

  9. azure sql database CPU troubleshooting

    描述 最新我们一个稳定运行快一年的项目突然出现CPU方面的性能问题,该项目使用的azure sql database  P2 500DTU,运维同事监控到CPU使用非常高,客户反馈系统运行也比较卡.看 ...

  10. PowerShell 操作 Azure SQL Active Geo-Replication 实战

    <Azure SQL Database Active Geo-Replication简介>一文中,我们比较全面的介绍了 Azure SQL Database Active Geo-Repl ...

随机推荐

  1. 走进AOP In .NET

    AOP是什么,有的译为面向方面编程,有的译为面向切面编程,我更加赞同后者.接下来,让我们一步步揭开AOP的面纱. AOP衍生自 编程中出现了一些用OOP技术无法捕捉和解决的问题.跟其他开发工具和思想一 ...

  2. html中的table导出Excel

    演示地址: http://www.jq22.com/yanshi3312 具体代码: <!DOCTYPE html> <html lang="zh-CN"> ...

  3. php-fpm 操作命令

    以下内容转自 https://www.cnblogs.com/alibai/p/4070076.html 和 https://blog.csdn.net/wzx19840423/article/det ...

  4. Zabbix监控详解

    Zabbix是什么 Zabbix 是由Alexei Vladishev创建,目前由Zabbix SIA在持续开发和支持. Zabbix 是一个企业级的分布式开源监控方案. Zabbix是一款能够监控各 ...

  5. [ActionScript 3.0] 对数组中的元素进行排序Array.sort()的方法

    对数组中的元素进行排序. 此方法按 Unicode 值排序. (ASCII 是 Unicode 的一个子集.) 默认情况下,Array.sort()按以下方式进行排序: 1. 排序区分大小写(Z优先于 ...

  6. 部署LNMP架构及其应用

    部署企业LNMP架构 (一)首先安装nginx服务,具体请见另一篇关于nginx的博文. (二)安装MySQL数据库 .安装前准备 [root@localhost ~]# rpm -e mysql-s ...

  7. PHP curl 上传文件版本兼容问题

    [摘要:做微疑开辟挪用微疑接心上传文件时,总是返回 {"errcode":41005,"errmsg":"media data missing hin ...

  8. 对cors的理解

    一.简介 CORS需要浏览器和服务器同时支持.目前,所有浏览器都支持该功能,IE浏览器不能低于IE10. 整个CORS通信过程,都是浏览器自动完成,不需要用户参与.对于开发者来说,CORS通信与同源的 ...

  9. iOS8 dismissViewControllerAnimated:YES在Show Segue不工作

    最近使用iOS8 Sdk(xcode6.1.1)使用Show Segue功能,V_A视图push到V_B视图,然后想通过使用按键返回V_A,我记得ios6的时候可以使用[self dismissVie ...

  10. TX1/TX2 Qt安装与配置

    安装Qt 安装Qt Creator,打开终端执行如下命令: sudo apt-get install qt5-default qtcreator -y 安装Qt示例和文档: sudo apt-get ...