首页 > 其他分享 >Autofac

Autofac

时间:2023-08-10 23:01:33浏览次数:34  
标签:容器 Autofac RegisterType builder autofac 泛型 public

AutoFac

(1)使用

  1. NuGet 引入包Autofac.Extention

  2. .net 6 program.cs 中 替換原生IOC容器, 此时原生的IOC容器中的东西被转移到Autofac里, 在ConfigureContainer中不注册也行, 不是并行状态

    // 替换原生IOC容器 => autofac容器
    builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  3. .net 6 program.cs 中 使用autofac容器

    1. 默认不写为瞬态

    2. InstancePerLifetimeScope() 线程

    3. .SingleInstance()单例

    //使用autofac容器
    builder.Host.ConfigureContainer<ContainerBuilder>(builder => 
            {
                builder.RegisterType<服务接口实现类>().As<服务接口类>().注册状态();
            });
  4. 使用

    namespace SecondDemo.Controllers
    {
        [ApiController]
        [Route("/api/[controller]/[action]")]
        public class TestAutofacController : ControllerBase
        {
            public IUserService UserService { get; }
    ​
            public TestAutofacController(IUserService userService)
            {
                UserService = userService;
            }
    ​
            [HttpGet(Name = "TestAutofacUser", Order = 0)]
            public string Get()
            {
                return UserService.GetUserName();
            }
        }
    }
  • 使用服务提供者, 查看容器是替换还是并行

    • autofac替换前是MicosoftExtensionServiceProviderEngineScope

    • 替换后是Autofac.Extension.DenpendencyInjection.AutoFacServiceProvider

public XxxController(IServceProvider, serviceProvider, IUserService userSerivce)
{
    this.UserService = userService
}

(2)泛型Service注入使用typeof()

public interface IBaseService<T>
{
    string GetTName(); 
}
public class BaseService<T> : IBaseService<T>
{
    /// <summary>
    /// 查找类的名字
    /// </summary>
    /// <returns>返回泛型的名字</returns>
    public string GetTName()
    {
        return typeof(T).Name;
    }
}

program.cs

  • autofac使用RegisterGeneric注入泛型

//原生注册泛型容器元素
builder.Services.AddTransient(typeof(IBaseService<>), typeof(BaseService<>));
//autofacf注入泛型容器元素
builder.Host.ConfigureContainer<ContainerBuilder>(builder => 
        {
            builder.RegisterGeneric(typeof(BaseService<>)).As(typeof(IBaseService<>));
        });

在开发时, 有一个习惯, 假如某个方法出现泛型类型, 就要在其下面写一个获取这个泛型的名称的方法

public class MyFactory
{
    public string SetFactory<T>()
    {
        return SetFactory(type(T));
    }
    //获取泛型名字
    public string SetFactory(Type type)
    {
        return type.Name;
    }
}

(3)autofac设置三种容器状态

  1. 默认不写为瞬态

  2. InstancePerLifetimeScope() 线程

  3. .SingleInstance()单例

//单例
builder.RegisterType<UserService>().As<IUserService>().SingleInstance();
       
//瞬态
builder.RegisterType<TransientService>().As<ITransientService>();
​
//线程
builder.RegisterType<SingletonService>().As<ISingletonService>().SingleInstance();
        builder.RegisterType<ScopedService>().As<IScopedService>().InstancePerLifetimeScope();

(4)通过属性注入

1.开启属性注入
  • .PropertiesAutowired(), 代表允许这个类中使用属性注入, 而不是代表这个类被属性注入

//使用autofac容器, 开启属性注入
builder.Host.ConfigureContainer<ContainerBuilder>(builder => 
        {
            builder.RegisterType<Service1>().As<IService1>().PropertiesAutowired();
            builder.RegisterType<Service2>().As<IService2>();
        });
  • 使用属性注入如下

public class Service1 : IService1
{
    public Service2 Service2 { get; set; }
}

(4)扩展方法封装Program.cs

builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    builder.AddSecondDemoApiModel();
});
public static class AutofacExtentions
{
    //扩展方法封装
    public static void AddSecondDemoApiModel(this ContainerBuilder builder)
    {
        builder.RegisterType<UserService>().As<IUserService>().SingleInstance();
        builder.RegisterType<TransientService>().As<ITransientService>();
        builder.RegisterType<SingletonService>().As<ISingletonService>().SingleInstance();
        builder.RegisterType<ScopedService>().As<IScopedService>().InstancePerLifetimeScope();
    }
}

标签:容器,Autofac,RegisterType,builder,autofac,泛型,public
From: https://www.cnblogs.com/phonk/p/17621830.html

相关文章

  • c#MVC使用AutoFac实现IoC容器,接口多个实现的注入
    AutoFac能够实现自动注入   NetCore同接口多个实现依赖注入  相关资料AutoFac下载的引入使用nuget包管理引入AutoFac 添加打勾的3个,AutoFac容器,AutoFac的apiController支持,AutoFac的mvc支持在Global.asax中注册AutoFacprotectedvoidApplication_Start()......
  • IOC认识及Autofac使用
    依赖注入学习DIP(DependencyInversion Principle)依赖倒置原则:上层模块不应该依赖于底层模块,二者应该通过抽象来依赖,依赖抽象而不是依赖细节。换言之,要针对接口编程,而不是针对实现编程。IOC(InversionofControl)控制反转:面向对象编程中的一种设计原则,可以用来减低计算机代......
  • .NET Core如何使用第三方容器Autofac
    首先先了解一下什么是AutofacAutofac用于在.NETCore应用程序中管理组件的生命周期和依赖关系。我们在开发一个项目的时在Program中注入依赖注入的生命周期,项目工程比较大的时候我们就要实现很多注入,最致命的缺点就是耽误太多时间,为解决这一问题的最好解决方法就是使用到Autof......
  • Autofac
    varasms=AppDomain.CurrentDomain.GetAssemblies().Where(x=>!x.GlobalAssemblyCache).ToArray();containerBuilder.RegisterAssemblyTypes(asms).Where(x=>typeof(IBaseView).IsAssignableFrom(x)).PublicOnly().AsSelf();containerBuilder.RegisterAssembl......
  • .NET Core依赖注入与Autofac注入介绍
    0前言本文主要介绍了ASP.NETCore自带的依赖注入框架的用法,然后针对原生框架的不足,介绍了更加完备的autofac框架的集成和使用。1.NETCore原生DI框架.NetCore自带一个依赖注入的框架,使用起来很是方便,不多说,先从简单示例做起。1.1简单示例以ASP.NETCoreweb的API项目为例......
  • 使用Autofac进行服务注册,适用版本.Net6(程序集、泛型)
    具体的也可以去参考官网:https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html首先在Program.cs所属的层中引用nuget包:Autofac.Extensions.DependencyInjectionnuget网址:https://www.nuget.org/packages 可以使用NuGet包管理器进行搜索安装在Program.cs中......
  • Autofac 3种常见注入IOC 以及生命周期
      ......
  • NET6使用AutoFac依赖注入(仓储模式)
    第一次使用autofac,然后net6最新长期支持的,就想着在net6的基础上使用autofac,我对依赖注入理解很差,一知半解的搞了好久。好在有了一点点的头绪,记录下省的以后忘记(突然发现自己以前用过的东西忘了好多……)首先你要有个仓储模式的项目、这个自己搭建吧在Program.cs文件中:配置程序......
  • autofac 实体层
      usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations.Schema;usingSystem.Linq;usingDapper.Lite;namespacewgh.model.Models{///<summary>///系统用户表///</summary>[Table("SysUserIn......
  • autofac 服务层
      usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingwgh.model.Models;usingDBHelper;usingIService;usingwgh.Service;namespaceService{///<summary>///系统用户服务层///<......