c # autofac in conjunction with WebApi

First, download the class library reference

  install-package Autofac

  install-package Autofac.Mvc4

  install-package Autofac.WebApi2

 

Second, the configuration autofac

 public class AutofacUtil
    {
        /// <summary>
        /// Autofac容器对象
        /// </summary>
        private static IContainer _container;

        /// <summary>
        /// 初始化autofac
        /// </summary>
        public static void InitAutofac()
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetCallingAssembly());
            builder.RegisterApiControllers(Assembly.GetCallingAssembly());

            //配置接口依赖
            builder.RegisterInstance<IDbConnection>(DBFactory.CreateConnection()).As<IDbConnection>();
            builder.RegisterGeneric(typeof(GenericRepository<>)).As(typeof(IGenericRepository<>));
            //注入仓储类
            builder.RegisterAssemblyTypes(Assembly.Load("Demo.Repository"))
                   .Where(x => x.Name.EndsWith("Repository"))
                   .AsImplementedInterfaces();

            _container = builder.Build();

            //设置MVC依赖注入
            DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));

            //设置WebApi依赖注入
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)_container);
        }

        /// <summary>
        /// 从Autofac容器获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetFromFac<T>()
        {
            return _container.Resolve<T>();
        }
    }

 

Third, registration autofac

  In the global file Global.asax Application_Start method add code

AutofacUtil.InitAutofac ();

 

Fourth, the use case

 public  class CodeController: BaseApiController 
    { 
        Private  Readonly ISMCodeRepository _smCodeRepository;
         public CodeController (ISMCodeRepository smCodeRepository) 
        { 
            _smCodeRepository = smCodeRepository; 
        } 

        ///  <Summary> 
        /// Get Data Dictionary list
         ///  </ Summary> 
        ///  <param name = "codeTypeNo"> data Dictionary type code </ param> 
        ///  <Returns> </ Returns> 
        [HttpPost]
         public ApiResult GetCodeList (SMCodeType codeTypeEntity) 
        { 
            var result = _smCodeRepository.GetCodeList(codeTypeEntity.CodeTypeNo);
            return new ApiResult() { Data = result.Select(x => new { x.CodeNo, x.CodeName }) };
        }
    }

 

Guess you like

Origin www.cnblogs.com/htsboke/p/10956807.html