码迷,mamicode.com
首页 > Windows程序 > 详细

c# autofac结合WebApi的使用

时间:2019-05-31 23:29:51      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:https   web   初始   result   api   logs   codec   文件中   ini   

原文:c# autofac结合WebApi的使用

一、下载相关类库引用

  install-package Autofac

  install-package Autofac.Mvc4

  install-package Autofac.WebApi2

 

二、配置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>();
        }
    }

 

三、注册autofac

  在Global.asax全局文件中Application_Start方法添加代码

AutofacUtil.InitAutofac();

 

四、使用案例

 public class CodeController : BaseApiController
    {
        private readonly ISMCodeRepository _smCodeRepository;
        public CodeController(ISMCodeRepository smCodeRepository)
        {
            _smCodeRepository = smCodeRepository;
        }

        /// <summary>
        /// 获取数据字典数据列表
        /// </summary>
        /// <param name="codeTypeNo">数据字典字典类型代码</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 }) };
        }
    }

 

c# autofac结合WebApi的使用

标签:https   web   初始   result   api   logs   codec   文件中   ini   

原文地址:https://www.cnblogs.com/lonelyxmas/p/10957825.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!