zoukankan      html  css  js  c++  java
  • 用Autofac替换.net core 内置容器

    官方建议使用内置容器,但有些功能并不支持,如下:
    • 属性注入
    • 基于名称的注入
    • 子容器
    • 自定义生存期管理
    • Func<T> 支持

    所以可以使用其他第三方IOC容器,如Autofac,下面为学习使用记录

    一、首先准备了一个接口和其实现类

    public interface ITestService
    {
        string ShowMsg();
    }
    复制代码
    public class TestService: ITestService
    {
        public string ShowMsg()
        {
            return "test123";
        }
    }
    复制代码

    二、安装Nuget 包

    Autofac
    Autofac.Extensions.DependencyInjection

    三、在 Startup.ConfigureServices 中配置容器

    注:使用第三方容器,Startup.ConfigureServices 必须返回 IServiceProvider。

      第一种方式,使用AutofacModule配置文件,原来代码修改为:

    复制代码
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        // Add Autofac
        var containerBuilder = new ContainerBuilder();
        containerBuilder.RegisterModule<AutofacModule>();
        containerBuilder.Populate(services);
        var container = containerBuilder.Build();
        return new AutofacServiceProvider(container);
    }
    复制代码

    AutofacModule类如:

    复制代码
    public class AutofacModule: Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<TestService>().As<ITestService>();
         //........... } }
    复制代码

      第二种方式

    Startup.ConfigureServices如下修改

    复制代码
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        // Add Autofac
        var containerBuilder = new ContainerBuilder();
        //containerBuilder.RegisterModule<AutofacModule>();
    
       //自动注册该程序集下的所有接口 //netcore_autofac 为程序集命名空间 //InstancePerLifetimeScope:同一个Lifetime生成的对象是同一个实例 //SingleInstance:单例模式,每次调用,都会使用同一个实例化的对象;每次都用同一个对象; //InstancePerDependency:默认模式,每次调用,都会重新实例化对象;每次请求都创建一个新的对象; containerBuilder.RegisterAssemblyTypes(Assembly.Load("netcore_autofac")).AsImplementedInterfaces().InstancePerLifetimeScope(); containerBuilder.Populate(services); var container = containerBuilder.Build(); return new AutofacServiceProvider(container); }
    复制代码

    其他Autofac在.net core 的使用,请参考官方文档:https://docs.autofac.org/en/latest/integration/aspnetcore.html

  • 相关阅读:
    iOS事件机制,以及不同手势使用touchesBegan等表现形式
    UIview 动画
    核心动画与UIView
    代理与Block
    关于清除浮动的几个写法
    关于一个自适应屏幕的高宽
    关于loading 的一个css样式
    用margin还是用padding?(3)—— 负margin实战
    jquery回顾part1——选择器
    解读mysql主从配置及其原理分析(Master-Slave)
  • 原文地址:https://www.cnblogs.com/soundcode/p/11548148.html
Copyright © 2011-2022 走看看