private void AutofacIoCRegister() { HttpConfiguration config = GlobalConfiguration.Configuration; if (_containerProvider != null) _containerProvider = null; var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)); Type baseType = typeof(IDependency); var assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList(); builder.RegisterAssemblyTypes(assemblies.ToArray()) .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract) .AsSelf() //自身服务,用于没有接口的类 .AsImplementedInterfaces() //接口服务 .PropertiesAutowired() //属性注入 .InstancePerLifetimeScope(); //保证生命周期基于请求 IContainer container = builder.Build(); _containerProvider = new ContainerProvider(container); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); //DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
注意
IDependency
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
时间: 2024-10-07 14:17:07