c# autofac结合WebApi的使用
程序员文章站
2022-06-28 20:06:01
一、下载相关类库引用 install-package Autofac install-package Autofac.Mvc4 install-package Autofac.WebApi2 二、配置autofac 三、注册autofac 在Global.asax全局文件中Application_S ......
一、下载相关类库引用
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 }) }; } }