ASP.NET Core MVC 项目 Autofac

目录

一:基本使用

二:简单理解Autofac容器

三:多种注册方式

四:构造函数注入

一:默认构造函数注入

二:选择一个构造函数参数的构造函数

五:属性注入

一:属性注入

二:属性注入扩展--指定属性注入

六:方法注入

七:单个对象多个实现

一:单个对象获取全部实现

二:单个对象获取单个实现

八:ASP.NET Core MVC 项目整合 Autofac

九:控制器属性注入

一:控制器属性注入

二:控制器属性注入--指定属性注入


一:基本使用

  1. 引入Nuget包:Autofac
  2. 创建容器
  3. 配置抽象和具体类之间的关系
  4. Build一下得到容器实例
  5. 获取对象实例

二:简单理解Autofac容器

using Autofac;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Study_ASP.NET_Core_MVC.ConsoleApp
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            //Autofac容器
            //1:引入Nuget包:Autofac
            //2:创建容器
            ContainerBuilder containerBuilder = new ContainerBuilder();
            //3:配置抽象和具体类之间的关系
            containerBuilder.RegisterType().As();
            //4:Build一下得到容器实例
            IContainer container = containerBuilder.Build();
            //5:获取对象实例
            IPhone iPhone = container.Resolve();
            //调用打电话方法
            iPhone.Call();
            //调用发短信方法
            iPhone.Text();
            Console.ReadLine();
        }
    }
    /// 
    /// Interfaces层
    /// 
    public interface IPhone
    {
        /// 
        /// 打电话方法
        /// 
        void Call();
        /// 
        /// 发短信方法
        /// 
        void Text();
    }
    /// 
    /// Services层
    /// 
    public class ApplePhone : IPhone
    {
        /// 
        /// 打电话方法
        /// 
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// 
        /// 发短信方法
        /// 
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
    }
}

三:多种注册方式


        public static void Main(string[] args)
        {
            //注册抽象和普通类
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                containerBuilder.RegisterType().As();
                IContainer container = containerBuilder.Build();
                IPhone iPhone = container.Resolve();
                iPhone.Call();
                iPhone.Text();
            }
            //注册具体实例
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                containerBuilder.RegisterInstance(new ApplePhone());
                IContainer container = containerBuilder.Build();
                IPhone iPhone = container.Resolve();
                iPhone.Call();
                iPhone.Text();
            }
            //注册泛型
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                containerBuilder.RegisterGeneric(typeof(List<>)).As(typeof(IList<>));
                IContainer container = containerBuilder.Build();
                IList< IPhone> iPhoneList = container.Resolve>();
                iPhoneList[0].Call();
                iPhoneList[0].Text();
            }
            //注册程序集
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                Assembly interfaceAssembly = Assembly.LoadFrom("Study ASP.NET Core MVC.Interfaces.dll");
                Assembly serviceAssembly = Assembly.LoadFrom("Study ASP.Net Core MVC.Services.dll");
                containerBuilder.RegisterAssemblyTypes(interfaceAssembly, serviceAssembly).AsImplementedInterfaces();
                IContainer container = containerBuilder.Build();
                IPhone iPhone = container.Resolve();
                iPhone.Call();
                iPhone.Text();
            }
            //注册抽象类和一段业务逻辑
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                containerBuilder.RegisterType().As();
                containerBuilder.Register(context =>
                {
                    //业务逻辑
                    return new ApplePhone();
                });
                IContainer container = containerBuilder.Build();
                IPhone iPhone = container.Resolve();
                iPhone.Call();
                iPhone.Text();
            }
            Console.ReadLine();
        }

四:构造函数注入

一:默认构造函数注入

using Autofac;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace Study_ASP.NET_Core_MVC.ConsoleApp
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            //构造函数注入
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                containerBuilder.RegisterType().As();
                containerBuilder.RegisterType().As();
                IContainer container = containerBuilder.Build();
                IPhone iPhone = container.Resolve();
                IPower Power =  container.Resolve();
                iPhone.Call();
                iPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// 
    /// Interfaces层
    /// 
    public interface IPhone
    {
        /// 
        /// 打电话方法
        /// 
        void Call();
        /// 
        /// 发短信方法
        /// 
        void Text();
    }
    public interface IPower
    {

    }
    /// 
    /// Services层
    /// 
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// 
        /// 带参构造函数
        /// 
        /// 
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower,IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// 
        /// 打电话方法
        /// 
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// 
        /// 发短信方法
        /// 
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
    }
    public class Power : IPower
    {

    }
}

二:选择一个构造函数参数的构造函数

using Autofac;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace Study_ASP.NET_Core_MVC.ConsoleApp
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            //构造函数注入
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                //如果有多个构造函数,默认选择构造函数中参数最多的构造函数
                //选择其中只有一个构造函数参数的构造函数
                containerBuilder.RegisterType().UsingConstructor(typeof(IPower)).As();
                containerBuilder.RegisterType().As();
                IContainer container = containerBuilder.Build();
                IPhone iPhone = container.Resolve();
                IPower Power =  container.Resolve();
                iPhone.Call();
                iPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// 
    /// Interfaces层
    /// 
    public interface IPhone
    {
        /// 
        /// 打电话方法
        /// 
        void Call();
        /// 
        /// 发短信方法
        /// 
        void Text();
    }
    public interface IPower
    {

    }
    /// 
    /// Services层
    /// 
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// 
        /// 带参构造函数
        /// 
        /// 
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower,IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// 
        /// 打电话方法
        /// 
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// 
        /// 发短信方法
        /// 
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
    }
    public class Power : IPower
    {

    }
}

五:属性注入

一:属性注入

using Autofac;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace Study_ASP.NET_Core_MVC.ConsoleApp
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            //属性注入
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                //表示支持属性注入
                containerBuilder.RegisterType().As().PropertiesAutowired();
                containerBuilder.RegisterType().As();
                IContainer container = containerBuilder.Build();
                //调试查看属性注入结果
                //在对象创建以后,自动给属性创建实例并赋值
                IPhone iPhone = container.Resolve();
                IPower Power =  container.Resolve();
                iPhone.Call();
                iPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// 
    /// Interfaces层
    /// 
    public interface IPhone
    {
        /// 
        /// 打电话方法
        /// 
        void Call();
        /// 
        /// 发短信方法
        /// 
        void Text();
    }
    public interface IPower
    {

    }
    /// 
    /// Services层
    /// 
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// 
        /// 带参构造函数
        /// 
        /// 
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower,IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// 
        /// 打电话方法
        /// 
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// 
        /// 发短信方法
        /// 
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
    }
    public class Power : IPower
    {

    }
}

二:属性注入扩展--指定属性注入

关键类CusotmSelectAttribute代码:


    /// 
    /// 指定属性注入
    /// 
    [AttributeUsage(AttributeTargets.Property)]
    public class CusotmSelectAttribute : Attribute
    {

    }

关键类CusotmPropertySelector代码:


    /// 
    /// 实现Autofac
    /// 判断属性
    /// 需要属性注入
    /// 
    public class CusotmPropertySelector : IPropertySelector
    {
        public bool InjectProperty(PropertyInfo propertyInfo,object instance)
        {
            //判断属性需要属性注入
            return propertyInfo.CustomAttributes.Any(c => c.AttributeType == typeof(CusotmSelectAttribute));
        }
    }

使用特性属性注入:

using Autofac;
using Autofac.Core;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace Study_ASP.NET_Core_MVC.ConsoleApp
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            //属性注入
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                //表示支持属性注入
                containerBuilder.RegisterType().As().PropertiesAutowired(new CusotmPropertySelector());
                containerBuilder.RegisterType().As();
                IContainer container = containerBuilder.Build();
                //调试查看属性注入结果
                //在对象创建以后,自动给属性创建实例并赋值
                IPhone iPhone = container.Resolve();
                IPower Power = container.Resolve();
                iPhone.Call();
                iPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// 
    /// Interfaces层
    /// 
    public interface IPhone
    {
        /// 
        /// 打电话方法
        /// 
        void Call();
        /// 
        /// 发短信方法
        /// 
        void Text();
    }
    public interface IPower
    {

    }
    /// 
    /// Services层
    /// 
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// 
        /// 标记支持属性注入特性
        /// 
        [CusotmSelect]
        public IPower Power { get; set; }
        /// 
        /// 带参构造函数
        /// 
        /// 
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower, IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// 
        /// 打电话方法
        /// 
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// 
        /// 发短信方法
        /// 
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
    }
    public class Power : IPower
    {

    }
    /// 
    /// 指定属性注入
    /// 
    [AttributeUsage(AttributeTargets.Property)]
    public class CusotmSelectAttribute : Attribute
    {

    }
    /// 
    /// 实现Autofac
    /// 判断属性
    /// 需要属性注入
    /// 
    public class CusotmPropertySelector : IPropertySelector
    {
        public bool InjectProperty(PropertyInfo propertyInfo,object instance)
        {
            //判断属性需要属性注入
            return propertyInfo.CustomAttributes.Any(c => c.AttributeType == typeof(CusotmSelectAttribute));
        }
    }
}

六:方法注入

using Autofac;
using Autofac.Core;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace Study_ASP.NET_Core_MVC.ConsoleApp
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            //方法注入
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                //表示支持方法注入
                containerBuilder.RegisterType().As().OnActivated(activa =>
                {
                    IPower iPower = activa.Context.Resolve();
                    activa.Instance.OpenPhone(iPower);
                });
                containerBuilder.RegisterType().As();
                IContainer container = containerBuilder.Build();
                //调试查看方法注入结果
                //在对象创建以后,自动给属性创建实例并赋值
                IPhone iPhone = container.Resolve();
                IPower Power = container.Resolve();
                iPhone.Call();
                iPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// 
    /// Interfaces层
    /// 
    public interface IPhone
    {
        /// 
        /// 打电话方法
        /// 
        void Call();
        /// 
        /// 发短信方法
        /// 
        void Text();
    }
    public interface IPower
    {

    }
    /// 
    /// Services层
    /// 
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// 
        /// 带参构造函数
        /// 
        /// 
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower, IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// 
        /// 打电话方法
        /// 
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// 
        /// 发短信方法
        /// 
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
        /// 
        /// 打开手机方法
        /// 
        /// 打开手机
        public void OpenPhone(IPower iPower)
        {
            Console.WriteLine("{0}打开手机", iPower);
        }
    }
    public class Power : IPower
    {

    }
}

七:单个对象多个实现

一:单个对象获取全部实现

using Autofac;
using Autofac.Core;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace Study_ASP.NET_Core_MVC.ConsoleApp
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                //单个抽象多个实现
                containerBuilder.RegisterType().As();
                containerBuilder.RegisterType().As();
                containerBuilder.RegisterType().As();
                IContainer container = containerBuilder.Build();
                //调试查看方法注入结果
                IPhone iPhone = container.Resolve();
                IPower Power = container.Resolve();
                IEnumerable iPhoneList = container.Resolve>();
                iPhone.Call();
                iPhone.Text();
                foreach(IPhone phone in iPhoneList)
                {
                    phone.Call();
                    phone.Text();
                }
            }
            Console.ReadLine();
        }
    }
    /// 
    /// Interfaces层
    /// 
    public interface IPhone
    {
        /// 
        /// 打电话方法
        /// 
        void Call();
        /// 
        /// 发短信方法
        /// 
        void Text();
    }
    public interface IPower
    {

    }
    /// 
    /// Services层
    /// 
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// 
        /// 带参构造函数
        /// 
        /// 
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower, IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// 
        /// 打电话方法
        /// 
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// 
        /// 发短信方法
        /// 
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
        /// 
        /// 打开手机方法
        /// 
        /// 打开手机
        public void OpenPhone(IPower iPower)
        {
            Console.WriteLine("{0}打开手机", iPower);
        }
    }
    public class VivoPhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// 
        /// 带参构造函数
        /// 
        /// 
        public VivoPhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public VivoPhone(IPower iPower, IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// 
        /// 打电话方法
        /// 
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// 
        /// 发短信方法
        /// 
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
        /// 
        /// 打开手机方法
        /// 
        /// 打开手机
        public void OpenPhone(IPower iPower)
        {
            Console.WriteLine("{0}打开手机", iPower);
        }
    }
    public class Power : IPower
    {

    }
}

二:单个对象获取单个实现

using Autofac;
using Autofac.Core;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace Study_ASP.NET_Core_MVC.ConsoleApp
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                //单个抽象多个实现
                containerBuilder.RegisterType().Keyed("ApplePhone");
                containerBuilder.RegisterType().Keyed("VivoPhone");
                containerBuilder.RegisterType().As();
                IContainer container = containerBuilder.Build();
                //调试查看方法注入结果,注入时指定标识,按照标识匹配创建对象
                IPhone applePhone = container.ResolveKeyed("ApplePhone");
                IPhone vivoPhone = container.ResolveKeyed("VivoPhone");
                applePhone.Call();
                vivoPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// 
    /// Interfaces层
    /// 
    public interface IPhone
    {
        /// 
        /// 打电话方法
        /// 
        void Call();
        /// 
        /// 发短信方法
        /// 
        void Text();
    }
    public interface IPower
    {

    }
    /// 
    /// Services层
    /// 
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// 
        /// 带参构造函数
        /// 
        /// 
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower, IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// 
        /// 打电话方法
        /// 
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// 
        /// 发短信方法
        /// 
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
        /// 
        /// 打开手机方法
        /// 
        /// 打开手机
        public void OpenPhone(IPower iPower)
        {
            Console.WriteLine("{0}打开手机", iPower);
        }
    }
    public class VivoPhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// 
        /// 带参构造函数
        /// 
        /// 
        public VivoPhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public VivoPhone(IPower iPower, IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// 
        /// 打电话方法
        /// 
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// 
        /// 发短信方法
        /// 
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
        /// 
        /// 打开手机方法
        /// 
        /// 打开手机
        public void OpenPhone(IPower iPower)
        {
            Console.WriteLine("{0}打开手机", iPower);
        }
    }
    public class Power : IPower
    {

    }
}

八:ASP.NET Core MVC 项目整合 Autofac

一:在当前项目右键管理Nuget包引入:Autofac和Autofac.Extensions.DependencyInjection

二:在当前项目中配置Autofac,修改Program.cs文件

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Study_ASP.Net_Core_MVC.Services;
using Study_ASP.NET_Core_MVC.Interfaces;

//表示整个应用程序,调用CreateBuilder方法创建一个WebApplicationBuilder对象。
var builder = WebApplication.CreateBuilder(args);
//向管道容器添加注册中间件
//添加注册控制器视图中间件
builder.Services.AddControllersWithViews();
//添加注册Session中间件
builder.Services.AddSession();

//添加注册Autofac中间件
//通过工厂替换整合Autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer(containerBuilder =>
{
    //注册服务
    containerBuilder.RegisterType().As();
    containerBuilder.RegisterType().As();
    containerBuilder.RegisterType().As();
});

//配置管道容器中间件,构造WebApplication实例
var app = builder.Build();
//判断是否是开发模式
if (!app.Environment.IsDevelopment())
{
    //向管道中添加中间件,该中间件将捕获异常、记录异常、重置请求路径并重新执行请求。
    app.UseExceptionHandler("/Shared/Error");
    //向管道中添加用于使用HSTS的中间件,该中间件添加了Strict Transport Security标头。默认值为30天
    app.UseHsts();
}
//向管道添加Session中间件
app.UseSession();
//向管道添加用于将HTTP请求重定向到HTTPS的中间件。
app.UseHttpsRedirection();
//向管道添加为当前请求路径启用静态文件服务
app.UseStaticFiles();
//向管道添加路由配置中间件
app.UseRouting();
//向管道添加鉴权中间件
app.UseAuthentication();
//向管道添加授权中间件
app.UseAuthorization();
//向管道添加默认路由中间件
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
//向管道添加启动应用程序中间件
app.Run();

三:控制器中应用Autofac

using Autofac;
using Microsoft.AspNetCore.Mvc;
using Study_ASP.Net_Core_MVC.Services;
using Study_ASP.NET_Core_MVC.Interfaces;
using Study_ASP.NET_Core_MVC.Models;
using System.Diagnostics;

namespace Study_ASP.NET_Core_MVC.Controllers
{
    public class HomeController : Controller
    {
        /// 
        /// 定义构造函数
        /// 
        private readonly ILogger _logger;
        private IPhone iPhone;
        private IMicroPhone microPhone;
        private IHeadPhone headPhone;
        private IEnumerable iPhoneList;
        /// 
        /// 初始化构造函数
        /// 
        /// 控制器构造函数
        /// 服务构造函数
        /// 上下文构造函数
        /// 自定义构造函数
        /// 自定义构造函数
        /// 自定义构造函数
        /// 自定义构造函数集合
        public HomeController(ILogger logger, IServiceProvider serviceProvider, IComponentContext componentContext, IPhone iPhone, IMicroPhone microPhone, IHeadPhone headPhone, IEnumerable iPhoneList)
        {
            //通过调试查看获取的数据
            _logger = logger;
            IHeadPhone iPhone1 = serviceProvider.GetService();
            IMicroPhone iPhone2 = componentContext.Resolve();
            this.iPhone = iPhone;
            this.microPhone = microPhone;
            this.headPhone = headPhone;
            this.iPhoneList = iPhoneList;
        }
        /// 
        /// Get请求
        /// Home控制器
        /// Index方法
        /// 
        /// 
        [HttpGet]
        public IActionResult Index()
        {
            //调用打电话方法
            iPhone.Call();
            //调用发短信方法
            iPhone.Text();
            //电泳显示实践方法
            ViewBag.ShowTime = iPhone.ShowTime(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));
            return View();
        }
    }
}

九:控制器属性注入

一:控制器属性注入

修改Program.cs文件

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Study_ASP.Net_Core_MVC.Services;
using Study_ASP.NET_Core_MVC.Interfaces;
using Study_ASP.NET_Core_MVC.Models;

//表示整个应用程序,调用CreateBuilder方法创建一个WebApplicationBuilder对象。
var builder = WebApplication.CreateBuilder(args);
//向管道容器添加注册中间件
//添加注册控制器视图中间件
builder.Services.AddControllersWithViews();
//添加注册Session中间件
builder.Services.AddSession();

//添加注册Autofac中间件
//通过工厂替换整合Autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer(containerBuilder =>
{
    //注册服务
    containerBuilder.RegisterType().As();
    containerBuilder.RegisterType().As();
    containerBuilder.RegisterType().As();
    //注册控制器和抽象关系
    var controllerBaseType = typeof(ControllerBase);
    //支持属性注入到ControllerBase中
    containerBuilder.RegisterAssemblyTypes(typeof(Program).Assembly).Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType).PropertiesAutowired();
});
//添加注册控制器属性注入
builder.Services.Replace(ServiceDescriptor.Transient());

//配置管道容器中间件,构造WebApplication实例
var app = builder.Build();
//判断是否是开发模式
if (!app.Environment.IsDevelopment())
{
    //向管道中添加中间件,该中间件将捕获异常、记录异常、重置请求路径并重新执行请求。
    app.UseExceptionHandler("/Shared/Error");
    //向管道中添加用于使用HSTS的中间件,该中间件添加了Strict Transport Security标头。默认值为30天
    app.UseHsts();
}
//向管道添加Session中间件
app.UseSession();
//向管道添加用于将HTTP请求重定向到HTTPS的中间件。
app.UseHttpsRedirection();
//向管道添加为当前请求路径启用静态文件服务
app.UseStaticFiles();
//向管道添加路由配置中间件
app.UseRouting();
//向管道添加鉴权中间件
app.UseAuthentication();
//向管道添加授权中间件
app.UseAuthorization();
//向管道添加默认路由中间件
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
//向管道添加启动应用程序中间件
app.Run();

修改控制器文件

using Autofac;
using Microsoft.AspNetCore.Mvc;
using Study_ASP.Net_Core_MVC.Services;
using Study_ASP.NET_Core_MVC.Interfaces;
using Study_ASP.NET_Core_MVC.Models;
using System.Diagnostics;

namespace Study_ASP.NET_Core_MVC.Controllers
{
    public class HomeController : Controller
    {
        /// 
        /// 定义构造函数
        /// 
        private readonly ILogger _logger;
        private IPhone iPhone;
        private IMicroPhone microPhone;
        private IHeadPhone headPhone;
        private IEnumerable iPhoneList;

        public IMicroPhone iMicroPhoneProp { get; set; }
        public IMicroPhone iMicroPhoneProp1 { get; set; }
        /// 
        /// 初始化构造函数
        /// 
        /// 控制器构造函数
        /// 服务构造函数
        /// 上下文构造函数
        /// 自定义构造函数
        /// 自定义构造函数
        /// 自定义构造函数
        /// 自定义构造函数集合
        public HomeController(ILogger logger, IServiceProvider serviceProvider, IComponentContext componentContext, IPhone iPhone, IMicroPhone microPhone, IHeadPhone headPhone, IEnumerable iPhoneList)
        {
            //通过调试查看获取的数据
            _logger = logger;
            IHeadPhone iPhone1 = serviceProvider.GetService();
            IMicroPhone iPhone2 = componentContext.Resolve();
            this.iPhone = iPhone;
            this.microPhone = microPhone;
            this.headPhone = headPhone;
            this.iPhoneList = iPhoneList;
        }
        /// 
        /// Get请求
        /// Home控制器
        /// Index方法
        /// 
        /// 
        [HttpGet]
        public IActionResult Index()
        {
            //调用打电话方法
            iPhone.Call();
            //调用发短信方法
            iPhone.Text();
            //电泳显示实践方法
            ViewBag.ShowTime = iPhone.ShowTime(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));
            return View();
        }
    }
}

二:控制器属性注入--指定属性注入

一:关键类CusotmSelectAttribute代码


    /// 
    /// 指定属性注入
    /// 
    [AttributeUsage(AttributeTargets.Property)]
    public class CusotmSelectAttribute : Attribute
    {

    }

二:关键类CusotmPropertySelector代码


    /// 
    /// 实现Autofac
    /// 判断属性
    /// 需要属性注入
    /// 
    public class CusotmPropertySelector : IPropertySelector
    {
        public bool InjectProperty(PropertyInfo propertyInfo,object instance)
        {
            //判断属性需要属性注入
            return propertyInfo.CustomAttributes.Any(c => c.AttributeType == typeof(CusotmSelectAttribute));
        }
    }

三:修改Program.cs文件

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Study_ASP.Net_Core_MVC.Services;
using Study_ASP.NET_Core_MVC.Interfaces;
using Study_ASP.NET_Core_MVC.Models;

//表示整个应用程序,调用CreateBuilder方法创建一个WebApplicationBuilder对象。
var builder = WebApplication.CreateBuilder(args);
//向管道容器添加注册中间件
//添加注册控制器视图中间件
builder.Services.AddControllersWithViews();
//添加注册Session中间件
builder.Services.AddSession();

//添加注册Autofac中间件
//通过工厂替换整合Autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer(containerBuilder =>
{
    //注册服务
    containerBuilder.RegisterType().As();
    containerBuilder.RegisterType().As();
    containerBuilder.RegisterType().As();
    //注册控制器和抽象关系
    var controllerBaseType = typeof(ControllerBase);
    //支持属性注入到ControllerBase中
    containerBuilder.RegisterAssemblyTypes(typeof(Program).Assembly).Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType).PropertiesAutowired(new CusotmPropertySelector());
});
//添加注册控制器属性注入
builder.Services.Replace(ServiceDescriptor.Transient());

//配置管道容器中间件,构造WebApplication实例
var app = builder.Build();
//判断是否是开发模式
if (!app.Environment.IsDevelopment())
{
    //向管道中添加中间件,该中间件将捕获异常、记录异常、重置请求路径并重新执行请求。
    app.UseExceptionHandler("/Shared/Error");
    //向管道中添加用于使用HSTS的中间件,该中间件添加了Strict Transport Security标头。默认值为30天
    app.UseHsts();
}
//向管道添加Session中间件
app.UseSession();
//向管道添加用于将HTTP请求重定向到HTTPS的中间件。
app.UseHttpsRedirection();
//向管道添加为当前请求路径启用静态文件服务
app.UseStaticFiles();
//向管道添加路由配置中间件
app.UseRouting();
//向管道添加鉴权中间件
app.UseAuthentication();
//向管道添加授权中间件
app.UseAuthorization();
//向管道添加默认路由中间件
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
//向管道添加启动应用程序中间件
app.Run();

三:修改控制器代码

using Autofac;
using Microsoft.AspNetCore.Mvc;
using Study_ASP.Net_Core_MVC.Services;
using Study_ASP.NET_Core_MVC.Interfaces;
using Study_ASP.NET_Core_MVC.Models;
using System.Diagnostics;

namespace Study_ASP.NET_Core_MVC.Controllers
{
    public class HomeController : Controller
    {
        /// 
        /// 定义构造函数
        /// 
        private readonly ILogger _logger;
        private IPhone iPhone;
        private IMicroPhone microPhone;
        private IHeadPhone headPhone;
        private IEnumerable iPhoneList;

        /// 
        /// 标识属性注入
        /// 
        [CusotmSelect]
        public IMicroPhone iMicroPhoneProp { get; set; }

        public IMicroPhone iMicroPhoneProp1 { get; set; }
        /// 
        /// 初始化构造函数
        /// 
        /// 控制器构造函数
        /// 服务构造函数
        /// 上下文构造函数
        /// 自定义构造函数
        /// 自定义构造函数
        /// 自定义构造函数
        /// 自定义构造函数集合
        public HomeController(ILogger logger, IServiceProvider serviceProvider, IComponentContext componentContext, IPhone iPhone, IMicroPhone microPhone, IHeadPhone headPhone, IEnumerable iPhoneList)
        {
            //通过调试查看获取的数据
            _logger = logger;
            IHeadPhone iPhone1 = serviceProvider.GetService();
            IMicroPhone iPhone2 = componentContext.Resolve();
            this.iPhone = iPhone;
            this.microPhone = microPhone;
            this.headPhone = headPhone;
            this.iPhoneList = iPhoneList;
        }
        /// 
        /// Get请求
        /// Home控制器
        /// Index方法
        /// 
        /// 
        [HttpGet]
        public IActionResult Index()
        {
            //调用打电话方法
            iPhone.Call();
            //调用发短信方法
            iPhone.Text();
            //电泳显示实践方法
            ViewBag.ShowTime = iPhone.ShowTime(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));
            return View();
        }
    }
}

你可能感兴趣的:(NET,.net,asp.net,.netcore,mvc)