Autofac IOC框架

时间:2022-04-20 18:49:04

ASP.NET Core自带了一个轻量级的IOC容器     但是只提供了最基本的AddXXX方法来绑定实例关系     需要一个一个添加   可以使用其他IOC容器来替换内置的

ABP自带Castle容器

1.安装Nuget包 Autofac 和 Autofac.Extensions.DependencyInjection

2.使用Autofac替换自带的IOC容器

在Startup.cs中如果ConfigureServices方法返回类型是void  改成IServiceProvider

先定义一个容器        public Autofac.IContainer ApplicationContainer { get; private set; }

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//实例化Autofac容器
var builder = new ContainerBuilder();
//将Services中的服务填充到Autofac中
builder.Populate(services);
//新模块组件注册
builder.RegisterModule<AutofacModuleRegister>();
//创建容器接收
var Container = builder.Build();
//这里可以不需要在上面定义ApplicationContainer 这句代码可以不要
//this.ApplicationContainer = Container;
//第三方IOC接管 core内置DI容器
return new AutofacServiceProvider(Container);

AutofacModuleRegister.cs

    public class AutofacModuleRegister : Autofac.Module
{
//重写Autofac管道Load方法,在这里注册注入
protected override void Load(ContainerBuilder builder)
{
//找到AutofacMvcDemo程序集中,以Service结尾的类,找到满足的类和实现的接口自动进行注册
builder.RegisterAssemblyTypes(GetAssemblyByName("JcbApplication")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();
//找到Program类型所在的程序集,以Repository结尾的类,找到满足的类和实现的接口自动进行注册
builder.RegisterAssemblyTypes(GetAssemblyByName("JcbApplication")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces(); //某个接口有多个实现类 需要特殊的进行手动注册 最后一个参数就是标识 字符串
builder.RegisterType<SqlService>().Named<ISqlService>(typeof(SqlService).Name);
builder.RegisterType<MySqlService>().Named<ISqlService>(typeof(MySqlService).Name); }
/// <summary>
/// 根据程序集名称获取程序集
/// </summary>
/// <param name="AssemblyName">程序集名称</param>
/// <returns></returns>
public static Assembly GetAssemblyByName(String AssemblyName)
{
return Assembly.Load(AssemblyName);
}
}

3.当一个接口有多个实例    使用的时候需要指定

    public class HomeController : Controller
{
private IPersonService _personService;
private ISqlService _sqlService;
private ISqlService _mysqlService;
private IComponentContext _componentContext;//Autofac上下文
public HomeController(IPersonService personService, IComponentContext componentContext)
{
this._personService = personService;
this._componentContext = componentContext;
this._sqlService = _componentContext.ResolveNamed<ISqlService>(typeof(SqlService).Name);
this._mysqlService = _componentContext.ResolveNamed<ISqlService>(typeof(MySqlService).Name);
}
public IActionResult Index()
{
var aa = _personService.GetData();
var bb = _sqlService.GetData();
var cc = _mysqlService.GetData();
return View();
}

多种不同的注册方式

https://www.cnblogs.com/bluesummer/p/8875702.html

//注册同一接口的多个实例

https://www.cnblogs.com/wei325/p/9191686.html