国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

游刃于MVC、WCF中的Autofac

2019-11-17 01:57:02
字體:
供稿:網(wǎng)友

游刃于MVC、WCF中的Autofac

為了程序的健壯性、擴展性、可維護性,依賴抽象而不是具體實現(xiàn)類等等,于是我選擇了Autofac依賴注入容器 就是這個工廠來降低耦合。之前買東西是自己去超市,現(xiàn)在呢 我需要什么東西,他們給送過來直接拿到了。

本例中將會分享

1.Autofac在Mvc的Controller控制器、Filter過濾器的使用

2.WCF中的使用

3.用Autofac來完成Unit Of Work工作單元模式 即同一個界限上下文內(nèi)可以共享同一個工作單元實例。這樣就可以統(tǒng)一提交,起到事務(wù)作用、數(shù)據(jù)統(tǒng)一性。一個http請求只有一個上下文實例也算是性能優(yōu)化吧, 在這里只用到工作單元的一些皮毛。

Demo全貌如下

  • Autofac.DataModel 采用database first的實體數(shù)據(jù)模型
  • Autofac.Repository實體泛型的倉儲模式 ,也可以簡單的理解是數(shù)據(jù)層
  • Autofac.CoreService 業(yè)務(wù)邏輯處理
  • Autofac.UnitOfWork 工作單元統(tǒng)一提交
  • Autofac.Controllers 控制器層是從Web層把所有控制器提取出來,這里用到區(qū)域Area
  • AutoFac.Web 前端采用的是MVVM模式的knockout.js ,還有autofac的配置
  • Autofac.ViewModel 視圖

  其中Repository、UnitOfWork、CoreService幾者之間調(diào)用接口或?qū)┢渌麑诱{(diào)用接口。

  從nuget獲取必要的Autofac程序包 Autofac、Autofac.Configuration、Autofac.Integration.Mvc、Autofac.Integration.Wcf

各個層依賴的是接口而不是具體實現(xiàn)類,Autofac是個工廠可以通過編譯的代碼xml配置文件兩種方式指定接口、實現(xiàn)類來完成注入實例。

這里用的是xml配置的方式,需要用到Autofac.Configuration程序集。這樣做有個明顯的好處:文件不需要編譯;不會擾亂各層關(guān)系。為什么這么說呢?如果用代碼來完成,web層就需要其他層的接口和實現(xiàn)類 也就是引用Repository、UnitOfWork、CoreService層,很明顯web層只需要引用Autofac.Controllers 就足夠了。而通過xml配置文件可以在bin目錄下找到具體的程序集如:Autofac.CoreService.dll

Autoface依賴注入在MVC里實現(xiàn)

Global.cs    

PRotected void application_Start()        {            //創(chuàng)建IOC容器            AutofacRegistion.BuildMvcContainer();            AutofacRegistion.BuildWcfContainer();            AreaRegistration.RegisterAllAreas();            WebApiConfig.Register(GlobalConfiguration.Configuration);            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);            RouteConfig.RegisterRoutes(RouteTable.Routes);        }
/// <summary>    /// 依賴注入Controller、FilterAtrribute、WCF    /// </summary>    public class AutofacRegistion    {        /// <summary>        /// 創(chuàng)建 MVC容器(包含F(xiàn)ilter)        /// </summary>        public static void BuildMvcContainer()        {            var builder = new ContainerBuilder();            //注冊Module方法2 在Web.config中配制方式            builder.RegisterModule(new ConfigurationSettingsReader("autofacMvc"));            //加載 *.Controllers 層的控制器,否則無法在其他層控制器構(gòu)造注入,只能在web層注入            Assembly[] asm = GetAllAssembly("*.Controllers.dll").ToArray();            builder.RegisterAssemblyTypes(asm);            //注冊倉儲            Assembly[] asmRepository = GetAllAssembly("*.Repository.dll").ToArray();            builder.RegisterAssemblyTypes(asmRepository)               .Where(t => t.Name.EndsWith("Repository"))               .AsImplementedInterfaces();

        //注入邏輯層也可以通過配置實現(xiàn)         //Assembly[] asmRepositoryService = GetAllAssembly("*.CoreService.dll").ToArray();         //builder.RegisterAssemblyTypes(asmRepositoryService).AsImplementedInterfaces();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());            builder.RegisterModelBinderProvider();                        //注冊過濾器             builder.RegisterFilterProvider();            builder.RegisterType<OperateAttribute>().PropertiesAutowired();            builder.RegisterControllers(typeof(MvcApplication).Assembly);            var container = builder.Build();            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));        }        /// <summary>        ///創(chuàng)建WCF的容器,不存放Controller、Filter        /// </summary>        public static void BuildWcfContainer()        {            var builder = new ContainerBuilder();            builder.RegisterModule(new ConfigurationSettingsReader("autofacWcf"));            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());            builder.RegisterModelBinderProvider();            var container = builder.Build();            //WCF IOC容器            AutofacHostFactory.Container = container;            //DependencyResolver.SetResolver(new AutofacDependencyResolver(container));        }        #region 加載程序集        public static List<Assembly> GetAllAssembly(string dllName)        {            List<string> pluginpath = FindPlugin(dllName);            var list = new List<Assembly>();            foreach (string filename in pluginpath)            {                try                {                    string asmname = Path.GetFileNameWithoutExtension(filename);                    if (asmname != string.Empty)                    {                        Assembly asm = Assembly.LoadFrom(filename);                        list.Add(asm);                    }                }                catch (Exception ex)                {                    Console.Write(ex.Message);                }            }            return list;        }        //查找所有插件的路徑        private static List<string> FindPlugin(string dllName)        {            List<string> pluginpath = new List<string>();                           string path = AppDomain.CurrentDomain.BaseDirectory;                string dir = Path.Combine(path, "bin");                string[] dllList = Directory.GetFiles(dir, dllName);                if (dllList.Length > 0)                {                    pluginpath.AddRange(dllList.Select(item => Path.Combine(dir, item.Substring(dir.Length + 1))));                }            return pluginpath;        }        #endregion    }

說明:

1 web.config還需要配置 globlal代碼中對應(yīng)的【autofacMvc】和【autofacWcf】節(jié)點

2 反射*.Controllers.dll獲取Autofac.Controllers程序集,實現(xiàn)注入

3反射*.Repository.dll獲取 Autofac.Repository程序集以'Repository'結(jié)尾的類的實例注入到它所繼承的接口,這個就不需要在xml中配置

4filter的注入和controller的注入方式不一樣

5 MVC和WCF注入實例分別存到兩個容器中。這就用到Autofac.Integration.Mvc、Autofac.Integration.Wcf兩個程序集。WCF注入的容器中不需要Controller、Filter,就可以把相關(guān)的反射和注冊去掉了。

web.config

<configSections>    <!-- autofac配置-->    <section name="autofacMvc" type="Autofac.Configuration.SectionHandler, Autofac.Configuration" />    <section name="autofacWcf" type="Autofac.Configuration.SectionHandler, Autofac.Configuration" />  </configSections>  <autofacMvc>    <files>      <file name="configs/CoreService.config" section="autofac" />    </files>  </autofacMvc>  <autofacWcf>    <files>      <!--<file name="configs/IocDAL.config" section="autofac" />-->    </files>  </autofacWcf>  <!--↑↑↑↑autofac配置結(jié)束↑↑↑↑-->

在上述webconfig中為了統(tǒng)一管理配置,具體指定接口、實現(xiàn)類、和注入實例的生命周期放到了configs/CoreService.config文件中

CoreService.config

<?xml version="1.0" encoding="utf-8"?><configuration>    <configSections>        <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/>    </configSections>    <autofac>        <components>      <!--DbContext上下文的生命周期為【per-lifetime-scope】即http請求的生命周期 -->      <component type="Autofac.DataModel.VehicleCheckDBEntities, Autofac.DataModel"                        service="System.Data.Entity.DbContext, EntityFramework"                       instance-scope="per-lifetime-scope"/>            <component type="Autofac.UnitOfWork.UnitOfWork, Autofac.UnitOfWork" service="Autofac.UnitOfWork.IUnitOfWork, Autofac.UnitOfWork" />                        <component type="Autofac.CoreService.Impl.UserManage, Autofac.CoreService" service="Autofac.CoreService.IUserManage, Autofac.CoreService" />            <component type="Autofac.CoreService.Impl.RoleManage, Autofac.CoreService" service="Autofac.CoreService.IRoleManage, Autofac.CoreService" />        </components>    </autofac></configuration>

說明:

1component組件配置中type、service配置的是實現(xiàn)類、程序集名稱(不是命名空間)、接口、程序集名稱。

2instance-scope 配置的是實例的生命周期。本例中用到兩種:

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 隆德县| 彰化县| 沐川县| 余姚市| 定南县| 肥乡县| 延安市| 抚顺市| 大冶市| 曲水县| 富民县| 永寿县| 丹凤县| 迭部县| 夏河县| 北碚区| 阳新县| 青铜峡市| 永登县| 岱山县| 中卫市| 宁武县| 垫江县| 西畴县| 鹰潭市| 中卫市| 白沙| 达拉特旗| 永州市| 黄梅县| 甘孜县| 昌宁县| 新邵县| 商南县| 洛宁县| 阿尔山市| 青铜峡市| 南皮县| 三都| 中江县| 靖西县|