首页 > 程序开发 > 综合编程 > 其他综合 >

c# autofac结合WebApi的使用 - 明明你也很爱我 - 博客园

2019-06-03

c autofac结合WebApi的使用 一、下载相关类库引用   install-packageAutofac   install-packageAutofac Mvc4   install-packageAutofac WebApi2 二、配置autofac public class AutofacUtil

c# autofac结合WebApi的使用 一、下载相关类库引用

  install-packageAutofac

  install-packageAutofac.Mvc4

  install-packageAutofac.WebApi2

二、配置autofac
 public class AutofacUtil
    {
        /// 
        /// Autofac容器对象
        /// 
        private static IContainer _container;

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

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

            //配置接口依赖
            builder.RegisterInstance(DBFactory.CreateConnection()).As();
            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);
        }

        /// 
        /// 从Autofac容器获取对象
        /// 
        /// 
        /// 
        public static T GetFromFac()
        {
            return _container.Resolve();
        }
    }

三、注册autofac

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

AutofacUtil.InitAutofac();

四、使用案例
 public class CodeController : BaseApiController
    {
        private readonly ISMCodeRepository _smCodeRepository;
        public CodeController(ISMCodeRepository smCodeRepository)
        {
            _smCodeRepository = smCodeRepository;
        }

        /// 
        /// 获取数据字典数据列表
        /// 
        /// 数据字典字典类型代码
        /// 
        [HttpPost]
        public ApiResult GetCodeList(SMCodeType codeTypeEntity)
        {
            var result = _smCodeRepository.GetCodeList(codeTypeEntity.CodeTypeNo);
            return new ApiResult() { Data = result.Select(x => new { x.CodeNo, x.CodeName }) };
        }
    }

相关文章
最新文章
热点推荐