IDependency自动注册autofac
ContainerBuilder builder = new ContainerBuilder(); builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>)); Type baseType = typeof(IDependency); // 获取所有相关类库的程序集 Assembly[] assemblies = ... builder.RegisterAssemblyTypes(assemblies) .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract) .AsImplementedInterfaces().InstancePerLifetimeScope();//InstancePerLifetimeScope 保证对象生命周期基于请求 IContainer container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));