zoukankan      html  css  js  c++  java
  • IOC容器2

    一、.NetCore 2.2版本

    RegisterType以普通类注册方式

    1、搭建.Net Core 2.2 项目,并添加组件

    2、创建Common类库,并添加TestService类

    代码如下:

    using System;
    
    namespace Common
    {
        public class TestService 
        {
            public string GetName()
            {
                return "功能点1";
            }
        }
    }

    3、配置

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Threading.Tasks;
    using Autofac;
    using Autofac.Extensions.DependencyInjection;
    using Common;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    
    namespace Core2._2
    {
        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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
                //注册Autofac组件
                return AutofacComponent.Register(services);
            }
            // 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();
                }
    
                app.UseMvc();
            }
        }
        public class AutofacComponent
        {
            /// <summary>
            /// 注册Autofac组件
            /// </summary>
            /// <param name="services"></param>
            /// <returns></returns>
            public static IServiceProvider Register(IServiceCollection services)
            {
                //实例化Autofac容器
                ContainerBuilder builder = new ContainerBuilder();
                //将collection中的服务填充到Autofac
                builder.Populate(services);
                //注册InstanceModule组件
                builder.RegisterModule<InstanceModule>();
                //创建容器
                IContainer container = builder.Build();
                //第三方容器接管Core内置的DI容器
                return new AutofacServiceProvider(container);
            }
        }
        public class InstanceModule : Autofac.Module
        {
            //重写Autofac管道中的Load方法,在这里注入注册的内容
            protected override void Load(ContainerBuilder builder)
            {
                //以普通类的形式注册PlayPianoService
                builder.RegisterType<TestService>();
            }
        }
    }

    4、访问

     代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Common;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    
    namespace Core2._2.Controllers
    {
        [Route("api/[controller]/[action]")]
        [ApiController]
        public class HomeController : ControllerBase
        {
            private readonly TestService _testService;
            public HomeController(TestService testService)
            {
                _testService = testService;
            }
            // GET: api/<controller>
            [HttpGet]
            public IEnumerable<string> Get()
            {
                var str = _testService.GetName();
    
                return new string[] { "value1", "value2" };
            }
        }
    }

    RegisterAssemblyTypes 查找匹配的类型注入方式

    1、配置RegisterAssemblyTypes自动注入方式映射接口和实现类

     代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Threading.Tasks;
    using Autofac;
    using Autofac.Extensions.DependencyInjection;
    using Common;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    
    namespace Core2._2
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
            public IConfiguration Configuration { get; }
            public IContainer ApplicationContainer { get; private set; }
            // This method gets called by the runtime. Use this method to add services to the container.
            public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
                //初始化容器
                var builder = new ContainerBuilder();
                //管道寄居
                builder.Populate(services);
                //业务逻辑层所在程序集命名空间
                Assembly service = Assembly.Load("Common");
                //接口层所在程序集命名空间
                Assembly repository = Assembly.Load("Common");
                //自动注入
                builder.RegisterAssemblyTypes(service, repository)
                    .Where(t => t.Name.EndsWith("Service"))
                    .AsImplementedInterfaces();
                //构造
                ApplicationContainer = builder.Build();
                //将AutoFac反馈到管道中
                return new AutofacServiceProvider(ApplicationContainer);
            }
            // 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();
                }
                app.UseMvc();
            }
        }
    }

    或者直接这样

    2、Common类

     代码如下:

    using System;
    
    namespace Common
    {
        public interface ITestService
        {
            string GetName();
        }
    
        public class TestService: ITestService
        {
            public string GetName()
            {
                return "功能点1";
            }
        }
    }

    访问

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Common;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    
    namespace Core2._2.Controllers
    {
        [Route("api/[controller]/[action]")]
        [ApiController]
        public class HomeController : ControllerBase
        {
            private readonly ITestService _testService;
            public HomeController(ITestService testService)
            {
                _testService = testService;
            }
            // GET: api/<controller>
            [HttpGet]
            public IEnumerable<string> Get()
            {
                var str = _testService.GetName();
    
                return new string[] { "value1", "value2" };
            }
        }
    }

     注意:RegisterAssemblyTypes 自动注入方式 接口注入方式(不可以通过实现类注入)否则:

    RegisterGeneric泛型的具体对象的方式

    1、

    二、.NET Core 3.0

    1、修改 Program.cs 将默认ServiceProviderFactory指定为AutofacServiceProviderFactory

     代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Autofac.Extensions.DependencyInjection;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    
    namespace IOCTest
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    //将默认ServiceProviderFactory指定为AutofacServiceProviderFactory
                    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                    });
        }
    }

    2、然后在 Startup.cs 中添加 ConfigureContainer 方法

    使用ConfigureContainer访问Autofac容器生成器,并直接向Autofac注册。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Threading.Tasks;
    using Autofac;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    
    namespace IOCTest
    {
        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 void ConfigureServices(IServiceCollection services) //Core 3.0 3.1 此方法都是void 类型   2.1 2.2则是返回IServiceCollection
            {
                services.AddControllers();
            }
    
            public void ConfigureContainer(ContainerBuilder builder)
            {
                //业务逻辑层所在程序集命名空间
                Assembly service = Assembly.Load("Common");
                //接口层所在程序集命名空间
                Assembly repository = Assembly.Load("Common");
                //自动注入
                builder.RegisterAssemblyTypes(service, repository)
                    .Where(t => t.Name.EndsWith("Service"))
                    .AsImplementedInterfaces();
                //注册仓储,所有IRepository接口到Repository的映射
            }
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }
        }
    
    }

    3、类库方法接口和实现类

     4、访问

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Common;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    
    namespace IOCTest.Controllers
    {
        [Route("api/[controller]/[action]")]
        [ApiController]
        public class HomeController : ControllerBase
        {
            private readonly ITestService _testService;
            public HomeController(ITestService testService)
            {
                _testService = testService;
            }
            // GET: api/<controller>
            [HttpGet]
            public IEnumerable<string> Get()
            {
                var str=_testService.GetName();
    
                return new string[] { "value1", "value2" };
            }
        }
    }
  • 相关阅读:
    9月9号作业
    9月9号笔记
    jupyter的补充
    jupyter的使用
    9月6号作业
    编程语言的分类
    计算机组成
    计算机组成的补充
    面向对象基础
    9月2号作业
  • 原文地址:https://www.cnblogs.com/fger/p/12131860.html
Copyright © 2011-2022 走看看