webapi框架搭建-依赖注入之autofac
webapi框架搭建系列博客
前言
c#的依赖注入框架有unity、autofac,两个博主都用过,感觉unity比较简单而autofac的功能相对更丰富(自然也更复杂一点),本篇将基于前几篇已经创建好的webapi项目,引入autofac功能。
前面我们已经搭建好webapi,并用了owin技术。这篇的autofac也将基于这两种技术进行开发。
步骤
引入包
using System.Reflection;
using Autofac;
using Autofac.Integration.WebApi;
using webapi.example; namespace webapi.AutoFac
{
public static class ContainerBuilerCommon
{
public static IContainer GetWebApiContainer()
{
var builder = new ContainerBuilder();
// 注册webapi的所有控制器
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// 注册一个用于测试的组件。
builder.RegisterType<Chinese>().As<People>();
return builder.Build();
}
}
}
除了builder.RegisterApiControllers(Assembly.GetExecutingAssembly())是注册webapi控制器,其它所有的代码都是autofac本身的用法。
autofac的用法可总结为三步:
1、创建container builder
var builder = new ContainerBuilder();
autofac怎么注册组件可以参考官网:http://autofac.readthedocs.io/en/latest/register/registration.html
3、生成依赖注入容器(如果是webapi则将容器传给webapi的DependencyResolver对象)
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
用于测试的people接口和两个接口的实现类如下
public interface People
{
string Language();
} public class Chinese : People
{
public string Language()
{
return "汉语";
}
} public class American:People
{
public string Language()
{
return "english";
}
}
owin管道配置
public class Startup
{
/// <summary>
/// owin的http请求管道配置函数
/// </summary>
/// <param name="app"></param>
public void Configuration(IAppBuilder app)
{
#region 写在前面的配置
// 获取webapi的配置
var config = WebApiConfig.OwinWebApiConfiguration(new HttpConfiguration());
// 获取webapi的依赖注入容器
var container = ContainerBuilerCommon.GetWebApiContainer();
// 配置webapi的依赖注入
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
#endregion #region owin组件注册(要注意顺序)
app.UseAutofacMiddleware(container);// 先注册autofac组件,需要依赖注入功能的组件在此后注册
app.UseAutofacWebApi(config);//注册AutofacWebApi组件后再注册WebApi组件
app.UseWebApi(config);
#endregion
}
WebApiConfig类代码如下(非核心代码)
using System.Web.Http; namespace webapi.Configs
{
/// <summary>
/// webapi 配置类
/// </summary>
public static class WebApiConfig
{ /// <summary>
/// 返回webapi的httpconfiguration配置
/// 用于webapi应用于owin技术时使用
/// </summary>
/// <returns></returns>
public static HttpConfiguration OwinWebApiConfiguration(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();//开启属性路由
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
return config;
}
}
}
测试依赖注入是否正常
创建IOCTestController控制器
/// <summary>
/// 本代码用来测试依赖注入是否正常
/// </summary>
namespace webapi.example
{
public class IOCTestController : ApiController
{
private People _people;
public IOCTestController(People people)
{
_people = people;
} public IHttpActionResult GetLanguage()
{
return Ok(_people.Language());
}
}
}
注意:控制器里的_people没有用new的方法去创建,而是交给了控制器的构造函数,并且控制器的创建已经配置成由autofac进行依赖注入,如下代码
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
所以autofac会在创建IOCTestController时用Chinese代替接口people
builder.RegisterType<Chinese>().As<People>();
测试结果如下:

webapi框架搭建-依赖注入之autofac的更多相关文章
- webapi框架搭建-日志管理log4net
前言 本篇讲怎么在前几篇已经创建好的项目里加上日志处理机制,我们采用Log4net技术.跟多的log4net技术的细节请查阅log4net的官网. log4net官网:http://logging.a ...
- webapi框架搭建系列博客
webapi框架搭建系列博客 webapi框架搭建-创建项目(一) webapi框架搭建-创建项目(二)-以iis为部署环境的配置 webapi框架搭建-创建项目(三)-webapi owin web ...
- webapi框架搭建-创建项目(三)-webapi owin
上一篇:创建项目(二) 在上一篇里,我们已经创建好了webapi应用,并已经部署到iis里,本篇讲如何用owin自宿主或是iis宿主来部署webapi应用. owin介绍 传统的asp.net网站只能 ...
- webapi框架搭建-数据访问ef code first
webapi框架搭建系列博客 为什么用ef? 我相信很多博友和我一样都有这种“选择困难症”,我曾经有,现在也有,这是技术人的一个通病——总想用“更完美”的方式去实现,导致在技术选择上犹豫不决,或总是推 ...
- ASP.NET MVC IOC依赖注入之Autofac系列(一)- MVC当中应用
话不多说,直入主题看我们的解决方案结构: 分别对上面的工程进行简单的说明: 1.TianYa.DotNetShare.Model:为demo的实体层 2.TianYa.DotNetShare.Repo ...
- webapi框架搭建-创建项目(二)-以iis为部署环境的配置
上篇:webapi快速框架搭建-创建项目(一) 在"创建项目(一)"这一篇里已经创建了一个空的项目,但项目上什么都没有,本篇描述如何将webapi配置成部署在iis上. 步骤 用n ...
- webapi框架搭建-webapi异常处理
webapi框架搭建系列博客 前言 上一篇我们已经完成了项目的日志管理,在项目开发中日志会经常记录程序中的异常,供后续问题排查使用.本篇讲如何在webapi里加入异常处理机制. 目的和原则 1.程序任 ...
- ASP.NET Core 中的框架级依赖注入
https://tech.io/playgrounds/5040/framework-level-dependency-injection-with-asp-net-core 作者: Gunnar P ...
- webapi框架搭建-安全机制(四)-可配置的基于角色的权限控制
webapi框架搭建系列博客 在上一篇的webapi框架搭建-安全机制(三)-简单的基于角色的权限控制,某个角色拥有哪些接口的权限是用硬编码的方式写在接口上的,如RBAuthorize(Roles = ...
随机推荐
- Android最佳性能实践(四)——布局优化技巧
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/43376527 在前面几篇文章其中.我们学习了怎样通过合理管理内存,以及高性能编码技 ...
- openstack初始化Glance数据库时报错解决方式
环境为win7+virtualbox 中的centos6.5 安装Glance 的包 yum install openstack-glance python-glanceclient -y 配置Gla ...
- 海量日志采集系统flume架构与原理
1.Flume概念 flume是分布式日志收集系统,将各个服务器的数据收集起来并发送到指定地方. Flume是Cloudera提供的一个高可用.高可靠.分布式的海量日志采集.聚合和传输的系统.Flum ...
- Uva 10550 Combination Lock
Sample Input0 30 0 305 35 5 350 20 0 207 27 7 270 10 0 109 19 9 190 0 0 0Sample Output13501350162016 ...
- svn搭建服务器--- 绝对好使---杜恩德
如何创建 SVN 服务器,并搭建自己的 SVN 仓库 听语音 | 浏览:1289 | 更新:2016-09-10 17:45 1 2 3 4 5 6 7 分步阅读 百度经验:jingyan.baidu ...
- MongoDB学习笔记(一)
最近有些时间,就抽空研究了一下MongoDB,我以前经常使用关系型数据库,如Oracle.MySQL,对MongoDB只是有些很肤浅的了解,最近下决心要好好研究一下,主要的参考书有两本:<Mon ...
- CentOS 7 学习(二) 配置Nginx反向代理
CentOS 7 学习(二) 配置Nginx反向代理 Nginx可以通过php-fpm来运行PHP程序,也可以转向apache,让apache调用php程序来运行. 不过对于Nginx来说,其反向代理 ...
- 智能合约语言 Solidity 教程系列6 - 结构体与映射
写在前面 Solidity 是以太坊智能合约编程语言,阅读本文前,你应该对以太坊.智能合约有所了解, 如果你还不了解,建议你先看以太坊是什么 本系列文章一部分是参考Solidity官方文档(当前最新版 ...
- 【python】input、int、if-else、注释、while、module(random.randint())语法示例
import random luckyNum=random.randint(2,9) i=1 while i<=3: guessNum=input("请你猜猜我的幸运号码:" ...
- iOS OC Swift3.0 TableView 中tableviewcell的线左边不到边界
Swift 3.0 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt index ...