//实例化容器 var builder = new ContainerBuilder(); //获取类型 var bastType = typeof(IAnimal); //获取上下文的dll文件 // 错误代码var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList();
var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList(); var AllServer = assemblys.SelectMany(s => s.GetTypes()).Where(u => bastType.IsAssignableFrom(u) && u != bastType); //注入控制器 builder.RegisterControllers(assemblys.ToArray()); //自动注入 builder.RegisterAssemblyTypes(assemblys.ToArray()) .Where(t => bastType.IsAssignableFrom(t) && t != bastType) .AsImplementedInterfaces().InstancePerLifetimeScope(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
运用一个公用的接口完成所有属性的实现ioc DI的依赖注入