ASP.NET Core 2.2--第三方依赖注入容器Autofact替换内置IServiceCollection容器

2021-03-21 10:24

阅读:401

标签:cse   override   services   running   原来   provider   send   col   int   

一、定制第三方依赖注入容器Autofac

1、nuget引入autofac和 Autofac.Extensions.DependencyInjection

技术图片

2、注释掉原来的IServiceCollection,ConfigureServices需要返回值IServiceProvider

3、new ContainerBuilder实例化容器

4、注册服务

  a、使用containerBuilder.RegisterType注册服务

  b、使用containerBuilder.RegisterModule注册服务,通过Module注册

5、返回AutofacServiceProvider 的实例

     #region 原来的IServiceCollection容器
        // This method gets called by the runtime. Use this method to add services to the container.
        //public void ConfigureServices(IServiceCollection services)
        //{
        //    services.Configure(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);
        //}
        #endregion

        /// 
        /// 整合Autofac
        /// 1、引入autofac Autofac.Extensions.DependencyInjection
        /// 2、ConfigureServices需要返返回值 IServiceProvider
        /// 3、实例化容器
        /// 4、注册服务
        /// 5、返回AutofacServiceProvider的实例
        /// 
        /// 
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure(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);
            //1、实例一个容器
            ContainerBuilder containerBuilder = new ContainerBuilder();

            //services默认的注册服务,还需要处理控制器实例相关的的工作。 
            containerBuilder.Populate(services); //autofac全权接管了之前这个Service的所有工作

            //2、注册服务
            containerBuilder.Register(a => new CustomAutofacAOP()); //autofac允许使用Aop
            //a、使用containerBuilder.RegisterType注册服务
            containerBuilder.RegisterType().As().SingleInstance();
            //b、使用containerBuilder.RegisterModule注册服务,通过Module注册
            containerBuilder.RegisterModule();
            IContainer container = containerBuilder.Build();

            return new AutofacServiceProvider(container);
        }

 注册服务

namespace Self.David.Core.Service.Utility
{
    public class CustomAutofacModule : Module
    {
        /// 
        ///  当前这Module专用做服务注册
        /// 
        /// 
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType().As().SingleInstance();
            builder.RegisterType().As().SingleInstance();
        }
    }
}

 接口

namespace Self.David.Core.Interface
{
    public interface IAnimal
    {
        void Running();
    }
}
namespace Self.David.Core.Interface
{
    public interface IMsg
    {
        void SendMsg();
    }
}
namespace Self.David.Core.Interface
{
    public interface IPhone
    {
        void Call();
    }
}

服务

namespace Self.David.Core.Service
{
public class ApplePhoneService : IPhone { public void Call() { Console.WriteLine($"{nameof(ApplePhoneService)}打电话!"); } } } namespace Self.David.Core.Service { public class DogService : IAnimal { public void Running() { Console.WriteLine($"{nameof(DogService)}奔跑!"); } } } namespace Self.David.Core.Service { public class SmsMsgService : IMsg { public void SendMsg() { Console.WriteLine($"{nameof(SmsMsgService)}发送消息!"); } } }

控制器

namespace Self.David.Core.MVC6.Controllers
{
    /// 
    /// 在服务中实现AOP
    /// Autofacr容器替换IServiceCollection容器
    /// 
    public class AutofacDIController : Controller
    {
        private IPhone _iPhone = null;
       
        public AutofacDIController(IPhone iPhone)
        {
            _iPhone = iPhone;
        }

        public IActionResult Index()
        {
            _iPhone.Call();
            return View();
        }
    }
}

 

    /// 
    /// Autofacr容器替换IServiceCollection容器
    /// 
    public class AutofacDIModuleController : Controller
    {
        private IAnimal _iAnimal = null;
        private IMsg _iMsg = null;

        public AutofacDIModuleController(IAnimal iAnimal, IMsg iMsg)
        {
            _iAnimal = iAnimal;
            _iMsg = iMsg;
        }

        public IActionResult Index()
        {
            _iAnimal.Running();//动物奔跑
            _iMsg.SendMsg();//发送消息
            return View();
        }
    }

开始在ConfigureServices里注册ApplePhoneService,当我们访问AutofacDIController,构造AutofacDIController的时候注入了ApplePhoneService,如下图所示

 技术图片

开始在ConfigureServices里通过Module方式注册DogService和SmsService,当我们访问AutofacDIModuleController,构造AutofacDIModuleController的时候注入了DogService和SmsService,如下图所示

 技术图片

技术图片

二、第三方容器Autofac和内置的容器IServiceCollection冲突吗?
不会冲突,autofac全权接管了之前IServiceCollection的所有工作

 

项目结构图

技术图片

ASP.NET Core 2.2--第三方依赖注入容器Autofact替换内置IServiceCollection容器

标签:cse   override   services   running   原来   provider   send   col   int   

原文地址:https://www.cnblogs.com/menglin2010/p/12721413.html


评论


亲,登录后才可以留言!