.net core3.1 实现autofac注入

autofac 是实现控制反转(IOC)的一种方式,如果不清楚IOC是什么,可以看看这个园友的文章(浅谈IOC---博客园----DebugLZQ,个人觉得写得挺简单易懂的

 

下面这些主要是一些运用

1. 添加引用nuget引用:

Autofac

Autofac.Extensions.DependencyInjection

2. 修改Program.cs

修改默认的服务提供工厂为AutofacServiceProviderFactory,

.UseServiceProviderFactory(new AutofacServiceProviderFactory())

3. 修改startup.cs

添加ConfigureContainer方法,此时就是添加注入服务方式,最常用的就是分单个服务注入或者多个服务注入

public void ConfigureContainer(ContainerBuilder builder)
{

} 

3.1 单个服务注入

  按接口注入:

builder.RegisterType<IEatService>().AsImplementedInterfaces();
//builder.RegisterType<EatService>().As<IEatService>();

  按实例注入

EatService eat = new EatService();
builder.RegisterInstance(eat).As<IEatService>();

3.2 批量服务注入

  按照加载指定的程序集名称的方式注入;这个示例注入了该程序集中所有的Service结尾的业务逻辑实现层,所以想要注入的服务必须以Service结尾。

Assembly servive = Assembly.Load("PApplication");
Assembly repository = Assembly.Load("PServer");
builder.RegisterAssemblyTypes(servive, repository)
       .Where(t => t.Name.EndsWith("Service"))
       .AsImplementedInterfaces();

  先加载所有应用程序域所有程序集再筛选指定的程序集;这个示例注入了添加了三个自定义属性的所有服务,对应.net core 注入服务的三种方式:AddSingleton,AddTransient,AddScoped, 对服务命名没有要求

//var _assably = AppDomain.CurrentDomain.GetAssemblies();
//var _needImpl = _assably.Where(c => c.FullName.StartsWith("PServer") || c.FullName.StartsWith("PApplication")).ToArray();

var _needImpl1= DependencyContext.Default.RuntimeLibraries.Where(o => o.Name.StartsWith("PServer")|| o.Name.StartsWith("PApplication")).Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();

builder.RegisterAssemblyTypes(_needImpl1)
                         .Where(t => t.GetCustomAttribute<ScopedAttribute>() != null)
                         .AsImplementedInterfaces()
                        .InstancePerLifetimeScope();
builder.RegisterAssemblyTypes(_needImpl1)
                       .Where(t => t.GetCustomAttribute<TransientAttribute>() != null)
                       .AsImplementedInterfaces()
                      .InstancePerDependency();

builder.RegisterAssemblyTypes(_needImpl1)
                        .Where(t => t.GetCustomAttribute<SingletonAttribute>() != null)
                        .AsImplementedInterfaces()
                       .SingleInstance();

上面获取所有应用程序集有两种方式,可以通过AppDomain的方式,AppDomain为应用程序域,GetAssemblies()只会获取到已加载到当前域的程序集,有时候获取不到引用的程序集(不知道为什么,bin文件里面也有相关的dll),所以这里换了一种方式用的DependencyContext的方式,引用了 Microsoft.Extensions.DependencyModel,DependencyContext.Default获取到当前应用依赖的所有对象(dll)

原文地址:https://www.cnblogs.com/roubaozidd/p/14518222.html