public class AutofacConfig { /// <summary> /// IOC注册 /// </summary> public static void Register() { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //批量注册程序集 var serviceDll = BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(ab => ab.GetName().Name.EndsWith("Service")).ToArray(); builder.RegisterAssemblyTypes(serviceDll).AsImplementedInterfaces().SingleInstance(); IContainer container = builder.Build(); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); //帮助类注入 AutofacHelper.RegisterContainer(container); } }
/// <summary> /// 依赖注入帮助类 /// </summary> public class AutofacHelper { private static IContainer _container; ///<summary> ///注册DIContainer ///</summary> ///<param name="container">Autofac.IContainer</param> /// public static void RegisterContainer(IContainer container) { _container = container; } ///<summary> ///获取服务(Single) ///</summary> ///<typeparam name="TService">组件类型</typeparam> ///<returns>返回获取的组件</returns> /// public static TService Resolve<TService>() { using (ILifetimeScope scope = _container.BeginLifetimeScope()) { return ResolutionExtensions.Resolve<TService>(scope); } } }
复制进项目 根据提示添加引用即可
标签:WebApi,Autofac,依赖,container,IContainer,builder,static,public From: https://www.cnblogs.com/5tomorrow/p/16985721.html