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<ApplePhone>().As<IPhone>();
            //4:Build一下得到容器实例
            IContainer container = containerBuilder.Build();
            //5:获取对象实例
            IPhone iPhone = container.Resolve<IPhone>();
            //调用打电话方法
            iPhone.Call();
            //调用发短信方法
            iPhone.Text();
            Console.ReadLine();
        }
    }
    /// <summary>
    /// Interfaces层
    /// </summary>
    public interface IPhone
    {
        /// <summary>
        /// 打电话方法
        /// </summary>
        void Call();
        /// <summary>
        /// 发短信方法
        /// </summary>
        void Text();
    }
    /// <summary>
    /// Services层
    /// </summary>
    public class ApplePhone : IPhone
    {
        /// <summary>
        /// 打电话方法
        /// </summary>
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// <summary>
        /// 发短信方法
        /// </summary>
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
    }
}

三:多种注册方式


        public static void Main(string[] args)
        {
            //注册抽象和普通类
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                containerBuilder.RegisterType<ApplePhone>().As<IPhone>();
                IContainer container = containerBuilder.Build();
                IPhone iPhone = container.Resolve<IPhone>();
                iPhone.Call();
                iPhone.Text();
            }
            //注册具体实例
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                containerBuilder.RegisterInstance(new ApplePhone());
                IContainer container = containerBuilder.Build();
                IPhone iPhone = container.Resolve<IPhone>();
                iPhone.Call();
                iPhone.Text();
            }
            //注册泛型
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                containerBuilder.RegisterGeneric(typeof(List<>)).As(typeof(IList<>));
                IContainer container = containerBuilder.Build();
                IList< IPhone> iPhoneList = container.Resolve<IList<IPhone>>();
                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>();
                iPhone.Call();
                iPhone.Text();
            }
            //注册抽象类和一段业务逻辑
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                containerBuilder.RegisterType<ApplePhone>().As<IPhone>();
                containerBuilder.Register<IPhone>(context =>
                {
                    //业务逻辑
                    return new ApplePhone();
                });
                IContainer container = containerBuilder.Build();
                IPhone iPhone = container.Resolve<IPhone>();
                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<ApplePhone>().As<IPhone>();
                containerBuilder.RegisterType<Power>().As<IPower>();
                IContainer container = containerBuilder.Build();
                IPhone iPhone = container.Resolve<IPhone>();
                IPower Power =  container.Resolve<IPower>();
                iPhone.Call();
                iPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// <summary>
    /// Interfaces层
    /// </summary>
    public interface IPhone
    {
        /// <summary>
        /// 打电话方法
        /// </summary>
        void Call();
        /// <summary>
        /// 发短信方法
        /// </summary>
        void Text();
    }
    public interface IPower
    {

    }
    /// <summary>
    /// Services层
    /// </summary>
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// <summary>
        /// 带参构造函数
        /// </summary>
        /// <param name="iPower"></param>
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower,IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// <summary>
        /// 打电话方法
        /// </summary>
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// <summary>
        /// 发短信方法
        /// </summary>
        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<ApplePhone>().UsingConstructor(typeof(IPower)).As<IPhone>();
                containerBuilder.RegisterType<Power>().As<IPower>();
                IContainer container = containerBuilder.Build();
                IPhone iPhone = container.Resolve<IPhone>();
                IPower Power =  container.Resolve<IPower>();
                iPhone.Call();
                iPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// <summary>
    /// Interfaces层
    /// </summary>
    public interface IPhone
    {
        /// <summary>
        /// 打电话方法
        /// </summary>
        void Call();
        /// <summary>
        /// 发短信方法
        /// </summary>
        void Text();
    }
    public interface IPower
    {

    }
    /// <summary>
    /// Services层
    /// </summary>
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// <summary>
        /// 带参构造函数
        /// </summary>
        /// <param name="iPower"></param>
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower,IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// <summary>
        /// 打电话方法
        /// </summary>
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// <summary>
        /// 发短信方法
        /// </summary>
        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<ApplePhone>().As<IPhone>().PropertiesAutowired();
                containerBuilder.RegisterType<Power>().As<IPower>();
                IContainer container = containerBuilder.Build();
                //调试查看属性注入结果
                //在对象创建以后,自动给属性创建实例并赋值
                IPhone iPhone = container.Resolve<IPhone>();
                IPower Power =  container.Resolve<IPower>();
                iPhone.Call();
                iPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// <summary>
    /// Interfaces层
    /// </summary>
    public interface IPhone
    {
        /// <summary>
        /// 打电话方法
        /// </summary>
        void Call();
        /// <summary>
        /// 发短信方法
        /// </summary>
        void Text();
    }
    public interface IPower
    {

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

    }
}

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

关键类CusotmSelectAttribute代码:


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

    }

关键类CusotmPropertySelector代码:


    /// <summary>
    /// 实现Autofac
    /// 判断属性
    /// 需要属性注入
    /// </summary>
    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<ApplePhone>().As<IPhone>().PropertiesAutowired(new CusotmPropertySelector());
                containerBuilder.RegisterType<Power>().As<IPower>();
                IContainer container = containerBuilder.Build();
                //调试查看属性注入结果
                //在对象创建以后,自动给属性创建实例并赋值
                IPhone iPhone = container.Resolve<IPhone>();
                IPower Power = container.Resolve<IPower>();
                iPhone.Call();
                iPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// <summary>
    /// Interfaces层
    /// </summary>
    public interface IPhone
    {
        /// <summary>
        /// 打电话方法
        /// </summary>
        void Call();
        /// <summary>
        /// 发短信方法
        /// </summary>
        void Text();
    }
    public interface IPower
    {

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

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

    }
    /// <summary>
    /// 实现Autofac
    /// 判断属性
    /// 需要属性注入
    /// </summary>
    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<ApplePhone>().As<IPhone>().OnActivated(activa =>
                {
                    IPower iPower = activa.Context.Resolve<IPower>();
                    activa.Instance.OpenPhone(iPower);
                });
                containerBuilder.RegisterType<Power>().As<IPower>();
                IContainer container = containerBuilder.Build();
                //调试查看方法注入结果
                //在对象创建以后,自动给属性创建实例并赋值
                IPhone iPhone = container.Resolve<IPhone>();
                IPower Power = container.Resolve<IPower>();
                iPhone.Call();
                iPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// <summary>
    /// Interfaces层
    /// </summary>
    public interface IPhone
    {
        /// <summary>
        /// 打电话方法
        /// </summary>
        void Call();
        /// <summary>
        /// 发短信方法
        /// </summary>
        void Text();
    }
    public interface IPower
    {

    }
    /// <summary>
    /// Services层
    /// </summary>
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// <summary>
        /// 带参构造函数
        /// </summary>
        /// <param name="iPower"></param>
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower, IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// <summary>
        /// 打电话方法
        /// </summary>
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// <summary>
        /// 发短信方法
        /// </summary>
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
        /// <summary>
        /// 打开手机方法
        /// </summary>
        /// <param name="iPower">打开手机</param>
        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<ApplePhone>().As<IPhone>();
                containerBuilder.RegisterType<VivoPhone>().As<IPhone>();
                containerBuilder.RegisterType<Power>().As<IPower>();
                IContainer container = containerBuilder.Build();
                //调试查看方法注入结果
                IPhone iPhone = container.Resolve<IPhone>();
                IPower Power = container.Resolve<IPower>();
                IEnumerable<IPhone> iPhoneList = container.Resolve<IEnumerable<IPhone>>();
                iPhone.Call();
                iPhone.Text();
                foreach(IPhone phone in iPhoneList)
                {
                    phone.Call();
                    phone.Text();
                }
            }
            Console.ReadLine();
        }
    }
    /// <summary>
    /// Interfaces层
    /// </summary>
    public interface IPhone
    {
        /// <summary>
        /// 打电话方法
        /// </summary>
        void Call();
        /// <summary>
        /// 发短信方法
        /// </summary>
        void Text();
    }
    public interface IPower
    {

    }
    /// <summary>
    /// Services层
    /// </summary>
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// <summary>
        /// 带参构造函数
        /// </summary>
        /// <param name="iPower"></param>
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower, IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// <summary>
        /// 打电话方法
        /// </summary>
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// <summary>
        /// 发短信方法
        /// </summary>
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
        /// <summary>
        /// 打开手机方法
        /// </summary>
        /// <param name="iPower">打开手机</param>
        public void OpenPhone(IPower iPower)
        {
            Console.WriteLine("{0}打开手机", iPower);
        }
    }
    public class VivoPhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// <summary>
        /// 带参构造函数
        /// </summary>
        /// <param name="iPower"></param>
        public VivoPhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public VivoPhone(IPower iPower, IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// <summary>
        /// 打电话方法
        /// </summary>
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// <summary>
        /// 发短信方法
        /// </summary>
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
        /// <summary>
        /// 打开手机方法
        /// </summary>
        /// <param name="iPower">打开手机</param>
        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<ApplePhone>().Keyed<IPhone>("ApplePhone");
                containerBuilder.RegisterType<VivoPhone>().Keyed<IPhone>("VivoPhone");
                containerBuilder.RegisterType<Power>().As<IPower>();
                IContainer container = containerBuilder.Build();
                //调试查看方法注入结果,注入时指定标识,按照标识匹配创建对象
                IPhone applePhone = container.ResolveKeyed<IPhone>("ApplePhone");
                IPhone vivoPhone = container.ResolveKeyed<IPhone>("VivoPhone");
                applePhone.Call();
                vivoPhone.Text();
            }
            Console.ReadLine();
        }
    }
    /// <summary>
    /// Interfaces层
    /// </summary>
    public interface IPhone
    {
        /// <summary>
        /// 打电话方法
        /// </summary>
        void Call();
        /// <summary>
        /// 发短信方法
        /// </summary>
        void Text();
    }
    public interface IPower
    {

    }
    /// <summary>
    /// Services层
    /// </summary>
    public class ApplePhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// <summary>
        /// 带参构造函数
        /// </summary>
        /// <param name="iPower"></param>
        public ApplePhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public ApplePhone(IPower iPower, IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// <summary>
        /// 打电话方法
        /// </summary>
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// <summary>
        /// 发短信方法
        /// </summary>
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
        /// <summary>
        /// 打开手机方法
        /// </summary>
        /// <param name="iPower">打开手机</param>
        public void OpenPhone(IPower iPower)
        {
            Console.WriteLine("{0}打开手机", iPower);
        }
    }
    public class VivoPhone : IPhone
    {
        private IPower iPower;
        private IPower iPower2;
        /// <summary>
        /// 带参构造函数
        /// </summary>
        /// <param name="iPower"></param>
        public VivoPhone(IPower iPower)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
        }
        public VivoPhone(IPower iPower, IPower iPower2)
        {
            Console.WriteLine("带参构造函数");
            this.iPower = iPower;
            this.iPower2 = iPower2;
        }
        /// <summary>
        /// 打电话方法
        /// </summary>
        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
        /// <summary>
        /// 发短信方法
        /// </summary>
        public void Text()
        {
            Console.WriteLine("{0}发短信", this.GetType().Name);
        }
        /// <summary>
        /// 打开手机方法
        /// </summary>
        /// <param name="iPower">打开手机</param>
        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 =>
{
    //注册服务
    containerBuilder.RegisterType<IMicroPhone>().As<MicroPhone>();
    containerBuilder.RegisterType<IHeadPhone>().As<HeadPhone>();
    containerBuilder.RegisterType<IPhone>().As<ApplePhone>();
});

//配置管道容器中间件,构造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
    {
        /// <summary>
        /// 定义构造函数
        /// </summary>
        private readonly ILogger<HomeController> _logger;
        private IPhone iPhone;
        private IMicroPhone microPhone;
        private IHeadPhone headPhone;
        private IEnumerable<IPhone> iPhoneList;
        /// <summary>
        /// 初始化构造函数
        /// </summary>
        /// <param name="logger">控制器构造函数</param>
        /// <param name="serviceProvider">服务构造函数</param>
        /// <param name="componentContext">上下文构造函数</param>
        /// <param name="iPhone">自定义构造函数</param>
        /// <param name="microPhone">自定义构造函数</param>
        /// <param name="headPhone">自定义构造函数</param>
        /// <param name="iPhoneList">自定义构造函数集合</param>
        public HomeController(ILogger<HomeController> logger, IServiceProvider serviceProvider, IComponentContext componentContext, IPhone iPhone, IMicroPhone microPhone, IHeadPhone headPhone, IEnumerable<IPhone> iPhoneList)
        {
            //通过调试查看获取的数据
            _logger = logger;
            IHeadPhone iPhone1 = serviceProvider.GetService<IHeadPhone>();
            IMicroPhone iPhone2 = componentContext.Resolve<IMicroPhone>();
            this.iPhone = iPhone;
            this.microPhone = microPhone;
            this.headPhone = headPhone;
            this.iPhoneList = iPhoneList;
        }
        /// <summary>
        /// Get请求
        /// Home控制器
        /// Index方法
        /// </summary>
        /// <returns></returns>
        [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 =>
{
    //注册服务
    containerBuilder.RegisterType<MicroPhone>().As<IMicroPhone>();
    containerBuilder.RegisterType<HeadPhone>().As<IHeadPhone>();
    containerBuilder.RegisterType<ApplePhone>().As<IPhone>();
    //注册控制器和抽象关系
    var controllerBaseType = typeof(ControllerBase);
    //支持属性注入到ControllerBase中
    containerBuilder.RegisterAssemblyTypes(typeof(Program).Assembly).Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType).PropertiesAutowired();
});
//添加注册控制器属性注入
builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());

//配置管道容器中间件,构造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
    {
        /// <summary>
        /// 定义构造函数
        /// </summary>
        private readonly ILogger<HomeController> _logger;
        private IPhone iPhone;
        private IMicroPhone microPhone;
        private IHeadPhone headPhone;
        private IEnumerable<IPhone> iPhoneList;

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

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

一:关键类CusotmSelectAttribute代码


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

    }

二:关键类CusotmPropertySelector代码


    /// <summary>
    /// 实现Autofac
    /// 判断属性
    /// 需要属性注入
    /// </summary>
    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 =>
{
    //注册服务
    containerBuilder.RegisterType<MicroPhone>().As<IMicroPhone>();
    containerBuilder.RegisterType<HeadPhone>().As<IHeadPhone>();
    containerBuilder.RegisterType<ApplePhone>().As<IPhone>();
    //注册控制器和抽象关系
    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<IControllerActivator, ServiceBasedControllerActivator>());

//配置管道容器中间件,构造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
    {
        /// <summary>
        /// 定义构造函数
        /// </summary>
        private readonly ILogger<HomeController> _logger;
        private IPhone iPhone;
        private IMicroPhone microPhone;
        private IHeadPhone headPhone;
        private IEnumerable<IPhone> iPhoneList;

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vin Cente

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值