찾다
데이터 베이스MySQL 튜토리얼mysql + 유창하게 NHibernate + WebAPI + Autofac


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으로 문의하세요.
图文详解mysql架构原理图文详解mysql架构原理May 17, 2022 pm 05:54 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于架构原理的相关内容,MySQL Server架构自顶向下大致可以分网络连接层、服务层、存储引擎层和系统文件层,下面一起来看一下,希望对大家有帮助。

mysql的msi与zip版本有什么区别mysql的msi与zip版本有什么区别May 16, 2022 pm 04:33 PM

mysql的msi与zip版本的区别:1、zip包含的安装程序是一种主动安装,而msi包含的是被installer所用的安装文件以提交请求的方式安装;2、zip是一种数据压缩和文档存储的文件格式,msi是微软格式的安装包。

mysql怎么去掉第一个字符mysql怎么去掉第一个字符May 19, 2022 am 10:21 AM

方法:1、利用right函数,语法为“update 表名 set 指定字段 = right(指定字段, length(指定字段)-1)...”;2、利用substring函数,语法为“select substring(指定字段,2)..”。

mysql怎么替换换行符mysql怎么替换换行符Apr 18, 2022 pm 03:14 PM

在mysql中,可以利用char()和REPLACE()函数来替换换行符;REPLACE()函数可以用新字符串替换列中的换行符,而换行符可使用“char(13)”来表示,语法为“replace(字段名,char(13),'新字符串') ”。

MySQL复制技术之异步复制和半同步复制MySQL复制技术之异步复制和半同步复制Apr 25, 2022 pm 07:21 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于MySQL复制技术的相关问题,包括了异步复制、半同步复制等等内容,下面一起来看一下,希望对大家有帮助。

mysql怎么将varchar转换为int类型mysql怎么将varchar转换为int类型May 12, 2022 pm 04:51 PM

转换方法:1、利用cast函数,语法“select * from 表名 order by cast(字段名 as SIGNED)”;2、利用“select * from 表名 order by CONVERT(字段名,SIGNED)”语句。

mysql怎么判断是否是数字类型mysql怎么判断是否是数字类型May 16, 2022 am 10:09 AM

在mysql中,可以利用REGEXP运算符判断数据是否是数字类型,语法为“String REGEXP '[^0-9.]'”;该运算符是正则表达式的缩写,若数据字符中含有数字时,返回的结果是true,反之返回的结果是false。

mysql怎么删除unique keymysql怎么删除unique keyMay 12, 2022 pm 03:01 PM

在mysql中,可利用“ALTER TABLE 表名 DROP INDEX unique key名”语句来删除unique key;ALTER TABLE语句用于对数据进行添加、删除或修改操作,DROP INDEX语句用于表示删除约束操作。

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전