首页 数据库 mysql教程 mysql + Fluently NHibernate + WebAPI + Autofac

mysql + Fluently NHibernate + WebAPI + Autofac

Feb 15, 2017 am 10:55 AM


MySQL、Fluently NHibernate、WebAPI、Autofac,对我来说每一个都是麻烦疙瘩,现在它们为了一个共同的项目而凑合到一起了。一路磕磕碰碰,现在貌似有了一点眉目。

作为一个步入老人痴呆帕金森阶段的老革命,我当然要马上将奋斗过程记录下来:

1、MySql + Fluently NHibernate

static ISessionFactory sessionFactory;public static ISession OpenSession(string connString, string[] assemblys)
{    if (sessionFactory == null)
    {
        sessionFactory = Fluently.Configure()
            .Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard.
                ConnectionString(connString))
            .Mappings(m =>
            {                foreach (var item in assemblys)
                {
                    m.FluentMappings.AddFromAssembly(Assembly.Load(item));
                }
            }).BuildSessionFactory();

    }    return sessionFactory.OpenSession();
}

OpenSession((connString: "server=192.168.0.211; user id=root; password=lt1234; database=pnavrds", assemblys: new string[] { "Pnavrds.Data" });
登录后复制
登录后复制

.NET和NHibernate并不天然支持mysql,所以要在项目添加对mysql.data.dll的引用。mysql.data.dll在mysql的安装目录里有。
比如在 C:\Program Files (x86)\MySQL\Connector.NET 6.9\Assemblies\v4.5

2、WebAPI
有关路由问题。
别看api与MVC很像,但是,MVC支持Area,而api并不。
但是开始时我并不知道。轻车熟路地加了个Area,一访问,直接404。
路由如下:

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.MapRoute(        "Test_default",        "Test/{controller}/{id}",        new { id = UrlParameter.Optional }
    );
}
登录后复制
登录后复制

咋办呢?难道各种控制器济济一堂一锅粥?后来网上查了资料,添加了一个路由,改为:

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.Routes.MapHttpRoute(        "Test_defaultAPI",        "api/Test/{controller}/{id}",        new { id = RouteParameter.Optional }
    );
    context.MapRoute(        "Test_default",        "Test/{controller}/{action}/{id}",        new { action = "Index", id = UrlParameter.Optional }
    );
}
登录后复制
登录后复制

注意,这样处理之后,同一个控制器,就有两个地址都可以访问。一个有区域,一个没有区域:

http://localhost/Pnavrds.API/api/Test/Dev3/10http://localhost/Pnavrds.API/api/Dev3/10
登录后复制
登录后复制

因为asp.net webapi并不支持区域,不管你这个控制器放在哪个文件夹、哪个命名空间下,它都顽强地解释到根目录下。我们上面做的努力,仅仅是多了一个含有区域名称的地址而已。

参考资料

3、Autofac
这个东东是个好东东。我现在都有点离不开它了。不然那么多实例需要构造,然后每个构造函数都N多参数,太麻烦。但是,因为了解不够,每次用它,好像都要费一些周折,并且很难调试。
这次也不例外。

1)提示System.Web.Http的版本不对。
引用的system.web.http.dll版本为5.2.3.0,但系统说跟5.2.0.0对应不上,编译时虽然可以通过,但有警告,建议在app.config里写些啥啥啥。我找遍了代码,都看不到哪里声明了5.2.0.0。

后来还是根据编译器的提示,将它给出的代码,加到web.config里,编译警告就没有了,运行就再无这个错误:

<runtime>    
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Iesi.Collections" culture="neutral" publicKeyToken="aa95f207798dfdb4" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Autofac" culture="neutral" publicKeyToken="17863af14b0044da" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.0" newVersion="3.5.0.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
登录后复制
登录后复制

附上编译信息:

4>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3247: 发现同一依赖程序集的不同版本间存在冲突。
在 Visual Studio 中,请双击此警告(或选择此警告并按 Enter)以修复冲突;否则,请将以下绑定重定向添加到应用程序配置文件中的“runtime”节点: 
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="System.Net.Http.Formatting" culture="neutral"
 publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /></dependentAssembly></assemblyBinding>
 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="Iesi.Collections" culture="neutral" 
 publicKeyToken="aa95f207798dfdb4" /><bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" /></dependentAssembly></assemblyBinding>
 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="Autofac" culture="neutral" publicKeyToken="17863af14b0044da"/>
 <bindingRedirect oldVersion="0.0.0.0-3.5.0.0" newVersion="3.5.0.0" /></dependentAssembly></assemblyBinding>
登录后复制

2)说控制器没有默认构造函数
这说明autofac没有正常运行,否则不会报这个错。构造实例正是autofac的工作。

后来改了autofac的builder内容。代码如下:

public class AutofacConfig
{    public static void BuildContainer()
    {        var builder = new ContainerBuilder();        //Infrastructure objects
        builder.RegisterApiControllers(typeof(WebApiApplication).Assembly);
        builder.RegisterAssemblyTypes(typeof(WebApiApplication).Assembly).AsImplementedInterfaces();

        builder.RegisterModule(new AutofacWebTypesModule());        //其他代码.....

        builder.RegisterModelBinderProvider();
        builder.RegisterFilterProvider();

        IContainer container = builder.Build();        //DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = (new AutofacWebApiDependencyResolver(container));
    }
}
登录后复制
登录后复制

MySQL、Fluently NHibernate、WebAPI、Autofac,对我来说每一个都是麻烦疙瘩,现在它们为了一个共同的项目而凑合到一起了。一路磕磕碰碰,现在貌似有了一点眉目。

作为一个步入老人痴呆帕金森阶段的老革命,我当然要马上将奋斗过程记录下来:

1、MySql + Fluently NHibernate

static ISessionFactory sessionFactory;public static ISession OpenSession(string connString, string[] assemblys)
{    if (sessionFactory == null)
    {
        sessionFactory = Fluently.Configure()
            .Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard.
                ConnectionString(connString))
            .Mappings(m =>
            {                foreach (var item in assemblys)
                {
                    m.FluentMappings.AddFromAssembly(Assembly.Load(item));
                }
            }).BuildSessionFactory();

    }    return sessionFactory.OpenSession();
}

OpenSession((connString: "server=192.168.0.211; user id=root; password=lt1234; database=pnavrds", assemblys: new string[] { "Pnavrds.Data" });
登录后复制
登录后复制

.NET和NHibernate并不天然支持mysql,所以要在项目添加对mysql.data.dll的引用。mysql.data.dll在mysql的安装目录里有。
比如在 C:\Program Files (x86)\MySQL\Connector.NET 6.9\Assemblies\v4.5

2、WebAPI
有关路由问题。
别看api与MVC很像,但是,MVC支持Area,而api并不。
但是开始时我并不知道。轻车熟路地加了个Area,一访问,直接404。
路由如下:

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.MapRoute(        "Test_default",        "Test/{controller}/{id}",        new { id = UrlParameter.Optional }
    );
}
登录后复制
登录后复制

咋办呢?难道各种控制器济济一堂一锅粥?后来网上查了资料,添加了一个路由,改为:

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.Routes.MapHttpRoute(        "Test_defaultAPI",        "api/Test/{controller}/{id}",        new { id = RouteParameter.Optional }
    );
    context.MapRoute(        "Test_default",        "Test/{controller}/{action}/{id}",        new { action = "Index", id = UrlParameter.Optional }
    );
}
登录后复制
登录后复制

注意,这样处理之后,同一个控制器,就有两个地址都可以访问。一个有区域,一个没有区域:

http://localhost/Pnavrds.API/api/Test/Dev3/10http://localhost/Pnavrds.API/api/Dev3/10
登录后复制
登录后复制

因为asp.net webapi并不支持区域,不管你这个控制器放在哪个文件夹、哪个命名空间下,它都顽强地解释到根目录下。我们上面做的努力,仅仅是多了一个含有区域名称的地址而已。

参考资料

3、Autofac
这个东东是个好东东。我现在都有点离不开它了。不然那么多实例需要构造,然后每个构造函数都N多参数,太麻烦。但是,因为了解不够,每次用它,好像都要费一些周折,并且很难调试。
这次也不例外。

1)提示System.Web.Http的版本不对。
引用的system.web.http.dll版本为5.2.3.0,但系统说跟5.2.0.0对应不上,编译时虽然可以通过,但有警告,建议在app.config里写些啥啥啥。我找遍了代码,都看不到哪里声明了5.2.0.0。

后来还是根据编译器的提示,将它给出的代码,加到web.config里,编译警告就没有了,运行就再无这个错误:

<runtime>    
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Iesi.Collections" culture="neutral" publicKeyToken="aa95f207798dfdb4" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Autofac" culture="neutral" publicKeyToken="17863af14b0044da" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.0" newVersion="3.5.0.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
登录后复制
登录后复制

附上编译信息:

4>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3247: 发现同一依赖程序集的不同版本间存在冲突。
在 Visual Studio 中,请双击此警告(或选择此警告并按 Enter)以修复冲突;否则,请将以下绑定重定向添加到应用程序配置文件中的“runtime”节点: 
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="System.Net.Http.Formatting" culture="neutral" 
publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /></dependentAssembly></assemblyBinding>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="Iesi.Collections" culture="neutral" 
publicKeyToken="aa95f207798dfdb4" /><bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" /></dependentAssembly></assemblyBinding>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="Autofac" culture="neutral" publicKeyToken="17863af14b0044da"/>
<bindingRedirect oldVersion="0.0.0.0-3.5.0.0" newVersion="3.5.0.0" /></dependentAssembly></assemblyBinding>
登录后复制

2)说控制器没有默认构造函数
这说明autofac没有正常运行,否则不会报这个错。构造实例正是autofac的工作。

后来改了autofac的builder内容。代码如下:

public class AutofacConfig
{    public static void BuildContainer()
    {        var builder = new ContainerBuilder();        //Infrastructure objects
        builder.RegisterApiControllers(typeof(WebApiApplication).Assembly);
        builder.RegisterAssemblyTypes(typeof(WebApiApplication).Assembly).AsImplementedInterfaces();

        builder.RegisterModule(new AutofacWebTypesModule());        //其他代码.....

        builder.RegisterModelBinderProvider();
        builder.RegisterFilterProvider();

        IContainer container = builder.Build();        //DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = (new AutofacWebApiDependencyResolver(container));
    }
}
登录后复制
登录后复制

以上就是mysql + Fluently NHibernate + WebAPI + Autofac的内容,更多相关内容请关注PHP中文网(www.php.cn)!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1664
14
CakePHP 教程
1421
52
Laravel 教程
1315
25
PHP教程
1266
29
C# 教程
1239
24
MySQL的角色:Web应用程序中的数据库 MySQL的角色:Web应用程序中的数据库 Apr 17, 2025 am 12:23 AM

MySQL在Web应用中的主要作用是存储和管理数据。1.MySQL高效处理用户信息、产品目录和交易记录等数据。2.通过SQL查询,开发者能从数据库提取信息生成动态内容。3.MySQL基于客户端-服务器模型工作,确保查询速度可接受。

laravel入门实例 laravel入门实例 Apr 18, 2025 pm 12:45 PM

Laravel 是一款 PHP 框架,用于轻松构建 Web 应用程序。它提供一系列强大的功能,包括:安装: 使用 Composer 全局安装 Laravel CLI,并在项目目录中创建应用程序。路由: 在 routes/web.php 中定义 URL 和处理函数之间的关系。视图: 在 resources/views 中创建视图以呈现应用程序的界面。数据库集成: 提供与 MySQL 等数据库的开箱即用集成,并使用迁移来创建和修改表。模型和控制器: 模型表示数据库实体,控制器处理 HTTP 请求。

MySQL和PhpMyAdmin:核心功能和功能 MySQL和PhpMyAdmin:核心功能和功能 Apr 22, 2025 am 12:12 AM

MySQL和phpMyAdmin是强大的数据库管理工具。1)MySQL用于创建数据库和表、执行DML和SQL查询。2)phpMyAdmin提供直观界面进行数据库管理、表结构管理、数据操作和用户权限管理。

解决数据库连接问题:使用minii/db库的实际案例 解决数据库连接问题:使用minii/db库的实际案例 Apr 18, 2025 am 07:09 AM

在开发一个小型应用时,我遇到了一个棘手的问题:需要快速集成一个轻量级的数据库操作库。尝试了多个库后,我发现它们要么功能过多,要么兼容性不佳。最终,我找到了minii/db,这是一个基于Yii2的简化版本,完美地解决了我的问题。

MySQL与其他编程语言:一种比较 MySQL与其他编程语言:一种比较 Apr 19, 2025 am 12:22 AM

MySQL与其他编程语言相比,主要用于存储和管理数据,而其他语言如Python、Java、C 则用于逻辑处理和应用开发。 MySQL以其高性能、可扩展性和跨平台支持着称,适合数据管理需求,而其他语言在各自领域如数据分析、企业应用和系统编程中各有优势。

laravel框架安装方法 laravel框架安装方法 Apr 18, 2025 pm 12:54 PM

文章摘要:本文提供了详细分步说明,指导读者如何轻松安装 Laravel 框架。Laravel 是一个功能强大的 PHP 框架,它 упростил 和加快了 web 应用程序的开发过程。本教程涵盖了从系统要求到配置数据库和设置路由等各个方面的安装过程。通过遵循这些步骤,读者可以快速高效地为他们的 Laravel 项目打下坚实的基础。

初学者的MySQL:开始数据库管理 初学者的MySQL:开始数据库管理 Apr 18, 2025 am 12:10 AM

MySQL的基本操作包括创建数据库、表格,及使用SQL进行数据的CRUD操作。1.创建数据库:CREATEDATABASEmy_first_db;2.创建表格:CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY,titleVARCHAR(100)NOTNULL,authorVARCHAR(100)NOTNULL,published_yearINT);3.插入数据:INSERTINTObooks(title,author,published_year)VA

解决MySQL模式问题:TheliaMySQLModesChecker模块的使用体验 解决MySQL模式问题:TheliaMySQLModesChecker模块的使用体验 Apr 18, 2025 am 08:42 AM

在使用Thelia开发电商网站时,我遇到了一个棘手的问题:MySQL模式设置不当,导致某些功能无法正常运行。经过一番探索,我找到了一个名为TheliaMySQLModesChecker的模块,它能够自动修复Thelia所需的MySQL模式,彻底解决了我的困扰。

See all articles