省略接口和类的实现,具体如上图:
using Autofac;
using System;
using System.Linq;
using System.Reflection;
namespace autofacBatchResolver
{
class Program
{
static void Main(string[] args)
{
var builder = DependencyResolver();
using (var container = builder.Build())
{
IFunciton1 fun = container.Resolve<IFunciton1>();
IService service = container.Resolve<IService>();
Console.WriteLine(service.GetUsers());
Console.WriteLine(fun.GetName());
}
Console.ReadLine();
}
static ContainerBuilder DependencyResolver()
{
var builder = new ContainerBuilder();
Type basetype = typeof(IDependency); //获取顶级接口类型
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => basetype.IsAssignableFrom(t) && t.IsClass) //查询继承自顶级接口IDependency的实现类,如果没有这句,则注册所有当前运行环境中接口实现类
.AsImplementedInterfaces().InstancePerLifetimeScope();
return builder;
}
}
}