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

一、定制第三方依赖注入容器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<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);
        //}
        #endregion

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

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

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

            return new AutofacServiceProvider(container);
        }

 注册服务

namespace Self.David.Core.Service.Utility
{
    public class CustomAutofacModule : Module
    {
        /// <summary>
        ///  当前这Module专用做服务注册
        /// </summary>
        /// <param name="builder"></param>
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<DogService>().As<IAnimal>().SingleInstance();
            builder.RegisterType<SmsMsgService>().As<IMsg>().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
{
    /// <summary>
    /// 在服务中实现AOP
    /// Autofacr容器替换IServiceCollection容器
    /// </summary>
    public class AutofacDIController : Controller
    {
        private IPhone _iPhone = null;
       
        public AutofacDIController(IPhone iPhone)
        {
            _iPhone = iPhone;
        }

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

 

    /// <summary>
    /// Autofacr容器替换IServiceCollection容器
    /// </summary>
    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的所有工作

 

项目结构图

posted @ 2020-04-18 09:05  David.Meng  阅读(662)  评论(0编辑  收藏  举报