ASP.NET Webアプリケーションのコアシリーズ(2) - ASP.NETコアの交換でAutofacの使用は、(アプリケーション間MVC)DIバッチ依存性の注入が来ます

オリジナル: ASP.NET Webアプリケーションのコアシリーズ(2) - ASP.NETコアの交換でAutofacの使用は、(アプリケーション間MVC)DIバッチ依存性の注入が来ます

主なASP.NETコアが内蔵されたそれらの中にDIバッチMVC依存性注入、この章では、DIを使用する方法をあなたと共有していきますを使用して共有する方法については最後の章ではAutofacがでASP.NETコアでバッチ依存性の注入を置き換えています。

PS:この章では、コンストラクタ・インジェクションの方法を採用する、次の章では、両方の属性注入方式をサポートするためにそれを有効にする方法を共有していきます。

表記:

図1に示すように、「I」が末尾に「リポジトリ」を始めと記憶層インターフェイス。最後に「リポジトリ」に蓄積層の実装。

2、「私は」最後の「サービス」を始めとサービス層インタフェース。最後に、両方の「サービス」を達成するためのサービス層。

次は正式に私たちはWebプロジェクトTianYa.DotNetShare.CoreAutofacMvcDemoを追加前章、当社のソリューションを初めて目に基づいて、テーマを入力します

MVCフレームワークASP.NETコアWebアプリケーション(.NETコア2.2)のために、このデモのWebプロジェクトでは、次のアセンブリを参照する必要があります。

1、TianYa.DotNetShare.Model私たちの物理層

2、TianYa.DotNetShare.Service当社のサービス層

図3は、TianYa.DotNetShare.Repository倉庫層、我々はストレージ層を使用すべきではない通常のWebプロジェクト、我々はここに引用IOCの依存性注入を実証することです

4、Autofac依存性注入ベース成分

.NETコア5、Autofac.Extensions.DependencyInjection依存注射補助成分

これは私たちのNuGetからAutofacとAutofac.Extensions.DependencyInjection必要の参照は、次の2つのパッケージをダウンロードするにはクリックしてください:

次に、我々は次のように、登録するためのWebプロジェクトAutofacModuleRegister.cs Autofacモジュールにクラスを追加します。

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

using Autofac;

namespace TianYa.DotNetShare.CoreAutofacMvcDemo
{
    /// <summary>
    /// 注册Autofac模块
    /// </summary>
    public class AutofacModuleRegister : Autofac.Module
    {
        /// <summary>
        /// 重写Autofac管道Load方法,在这里注册注入
        /// </summary>
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterAssemblyTypes(GetAssemblyByName("TianYa.DotNetShare.Repository"))
                .Where(a => a.Name.EndsWith("Repository"))
                .AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(GetAssemblyByName("TianYa.DotNetShare.Service"))
                .Where(a => a.Name.EndsWith("Service"))
                .AsImplementedInterfaces();

            //注册MVC控制器(注册所有到控制器,控制器注入,就是需要在控制器的构造函数中接收对象)
            builder.RegisterAssemblyTypes(GetAssemblyByName("TianYa.DotNetShare.CoreAutofacMvcDemo"))
                .Where(a => a.Name.EndsWith("Controller"))
                .AsImplementedInterfaces();
        }

        /// <summary>
        /// 根据程序集名称获取程序集
        /// </summary>
        /// <param name="assemblyName">程序集名称</param>
        public static Assembly GetAssemblyByName(string assemblyName)
        {
            return Assembly.Load(assemblyName);
        }
    }
}
复制代码

然后打开我们的Startup.cs文件进行注入工作,如下所示:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using Autofac;
using Autofac.Extensions.DependencyInjection;

namespace TianYa.DotNetShare.CoreAutofacMvcDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            return RegisterAutofac(services); //注册Autofac
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

        /// <summary>
        /// 注册Autofac
        /// </summary>
        private IServiceProvider RegisterAutofac(IServiceCollection services)
        {
            //实例化Autofac容器
            var builder = new ContainerBuilder();
            //将services中的服务填充到Autofac中
            builder.Populate(services);
            //新模块组件注册    
            builder.RegisterModule<AutofacModuleRegister>();
            //创建容器
            var container = builder.Build();
            //第三方IoC容器接管Core内置DI容器 
            return new AutofacServiceProvider(container);
        }
    }
}
复制代码

PS:需要将自带的ConfigureServices方法的返回值改成IServiceProvider

接下来我们来看看控制器里面怎么弄:

复制代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TianYa.DotNetShare.CoreAutofacMvcDemo.Models;

using TianYa.DotNetShare.Service;
using TianYa.DotNetShare.Repository;

namespace TianYa.DotNetShare.CoreAutofacMvcDemo.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// 定义仓储层学生抽象类对象
        /// </summary>
        protected IStudentRepository StuRepository;

        /// <summary>
        /// 定义服务层学生抽象类对象
        /// </summary>
        protected IStudentService StuService;

        /// <summary>
        /// 通过构造函数进行注入
        /// 注意:参数是抽象类,而非实现类,因为已经在Startup.cs中将实现类映射给了抽象类
        /// </summary>
        /// <param name="stuRepository">仓储层学生抽象类对象</param>
        /// <param name="stuService">服务层学生抽象类对象</param>
        public HomeController(IStudentRepository stuRepository, IStudentService stuService)
        {
            this.StuRepository = stuRepository;
            this.StuService = stuService;
        }

        public IActionResult Index()
        {
            var stu1 = StuRepository.GetStuInfo("10000");
            var stu2 = StuService.GetStuInfo("10001");
            string msg = $"学号:10000,姓名:{stu1.Name},性别:{stu1.Sex},年龄:{stu1.Age}<br />";
            msg += $"学号:10001,姓名:{stu2.Name},性别:{stu2.Sex},年龄:{stu2.Age}";

            return Content(msg, "text/html", System.Text.Encoding.UTF8);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
复制代码

至此完成处理,接下来就是见证奇迹的时刻了,我们来访问一下/home/index,看看是否能返回学生信息。

可以发现,返回了学生的信息,说明我们注入成功了。

至此,本章就介绍完了,如果你觉得这篇文章对你有所帮助请记得点赞哦,谢谢!!!

demo源码:

链接:https://pan.baidu.com/s/1un6_wgm6w_bMivPPRGzSqw 
提取码:lt80

 

版权声明:如有雷同纯属巧合,如有侵权请及时联系本人修改,谢谢!!!

おすすめ

転載: www.cnblogs.com/lonelyxmas/p/12154055.html