在之前的项目中用来解耦的使用的轻型IOC框架是unity,它的使用也是很方便的提供在之前的文章的也提到过它的使用方式,但是使用久了之后发现了它的不足之处就是需要配置xml文件来对应的接口和实现的关系。总觉这种不够灵活。因为随着项目的进行需要配置的接口和实现会越来越多。配置起来很是麻烦还容易出错。我在想有没有别的IOC框架能够一劳永逸的实现解耦而不是通过配置呢。

答案是肯定的。 那就是autofac ,这是我在Github 上找到的轻型的IOC框架。它的使用方式也特别的简单。原理呢简单来说。是通过遍历程序集来实现的(PS:当然它也是支持通过配置文件来实现的这里我就不详细说了)。详细的信息呢大家可以轻易autofac 的官网下载源码来看。网址是 http://autofac.org/  它的最大特色呢就是约定实现。什么是约定实现。意思就是说你的接口和现实之间需要一个默认的约定。就跟创建控制器一样必须以controller来结尾一样。

下面我就直接贴代码了这个是我做的一个dome 是在在MVC5 webapi 中实现的注入

当然在是用之前你需要在安装几个包。直接nuget就行了一共需要三个包

按顺序说明下

step1 PM> Install-Package Autofac -Version 3.5.0 直接在包管理里面输入这个命令  nuget地址是https://www.nuget.org/packages/Autofac/3.5.0

step2 PM> Install-Package Autofac.Mvc5 添加这个包  nuget地址是https://www.nuget.org/packages/Autofac.Mvc5/

step3 PM> Install-Package Autofac.WebApi 最后是添加autofac webapi的包 https://www.nuget.org/packages/Autofac.WebApi/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi; namespace WebApiIoc.App_Start
{
public static class autofaconfig
{
public static void Initialize(HttpConfiguration config)
{
Initialize(config, RegisterServices(new ContainerBuilder()));//初始化容器
} public static void Initialize(HttpConfiguration config, IContainer container)
{
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);//注册api容器
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//注册MVC容器
} private static IContainer RegisterServices(ContainerBuilder builder)
{
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());//注册api容器的实现 builder.RegisterControllers(Assembly.GetExecutingAssembly());//注册mvc容器的实现 builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())//查找程序集中以services结尾的类型
.Where(t => t.Name.EndsWith("Services"))
.AsImplementedInterfaces();
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())//查找程序集中以Repository结尾的类型
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces(); return builder.Build();//返回容器
}
}
}

 这个是autofac的配置文件。

下面是webapiconfig文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebApiIoc.App_Start; namespace WebApiIoc
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services // Web API routes
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//注册webapi和mvc容器
autofaconfig.Initialize(config);
}
}
}

最后是global文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using WebApiIoc.App_Start; namespace WebApiIoc
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles); }
}
}

在apicontroller和MVCcontroller里面都是通过构造函数注入的方式实现的下面贴出来代码

这个是MVC

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Iservices;
using Microsoft.Ajax.Utilities; namespace WebApiIoc.Controllers
{
public class HomeController : Controller
{
private IOneServices _oneServices; public HomeController(IOneServices oneServices)
{
_oneServices = oneServices; } public ActionResult Index()
{
var sum = _oneServices.sum(, ); var aa = DependencyResolver.Current.GetService<IOneServices>(); ; ViewBag.Title = sum; return View();
}
}
}

这个是webapi

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Dependencies;
using Autofac;
using Autofac.Integration.WebApi;
using Iservices; namespace WebApiIoc.Controllers
{
public class ValuesController : ApiController
{ private IOneServices _oneServices; public ValuesController(IOneServices oneServices) {
_oneServices = oneServices; } // GET api/values
public IEnumerable<string> Get()
{
var sum = _oneServices.sum(, );return new string[] { "value1", "value2" };
} // GET api/values/5
public string Get(int id)
{
return "value";
} // POST api/values
public void Post([FromBody]string value)
{
} // PUT api/values/5
public void Put(int id, [FromBody]string value)
{
} // DELETE api/values/5
public void Delete(int id)
{
}
}
}

最后说明下如果你没有通过构造函数注入你又想获取实例的话怎么做呢。下面分别说明

MVC

          var OneServices = DependencyResolver.Current.GetService<IOneServices>();

Webapi

            IDependencyScope dependencyScope = this.Request.GetDependencyScope();
ILifetimeScope requestLifetimeScope = dependencyScope.GetRequestLifetimeScope();
var customerService = requestLifetimeScope.Resolve<IOneServices>();

其他的比如属性注入和方法注入就不在这写了。这里只是写的常用的简单的注册方式,后面我会把这部分注册的方式给补上.

基本到这里整个注册流程就完事了。以上写的不足之处请指出我会修正。希望和大家共同成长.

autofac使用笔记的更多相关文章

  1. IoC容器Autofac学习笔记

    一.一个没有使用IoC的例子 IoC的全称是Inversion of Control,中文叫控制反转.要理解控制反转,可以看看非控制反转的一个例子. public class MPGMovieList ...

  2. C# 读Autofac源码笔记(2)

    刚看了下Autofac属性注入的源码 首先看看WithProperty方法   image.png Autofac将我们的属性值,存在了一个list集合中   image.png 然后将这个集合传递到 ...

  3. C# 读Autofac源码笔记(1)

    最近在看Autofac的源码. Autofac据说是.net中最快的IOC框架,具体没有实验,于是看看Autofac具体是怎样实例化实体.   image.png 如上图所示,Autofac使用的是表 ...

  4. 《你必须知道的.NET》读书笔记三:体验OO之美

    此篇已收录至<你必须知道的.Net>读书笔记目录贴,点击访问该目录可以获取更多内容. 一.依赖也是哲学 (1)本质诠释:“不要调用我们,我们会调用你” (2)依赖和耦合: ①无依赖,无耦合 ...

  5. Asp.Net MVC 之 Autofac 初步使用2 集成mvc 属性注入以及自动注入

    首先看下Demo2的结构     然后下面一步步将Autofac集成到mvc中. 首先,定义Model Product.cs public class Product { public int Id ...

  6. 【AutoFac】依赖注入和控制反转的使用

    在开始之前首先解释一下我认为的依赖注入和控制反转的意思.(新手理解,哪里说得不正确还请指正和见谅) 控制反转:我们向IOC容器发出获取一个对象实例的一个请求,IOC容器便把这个对象实例“注入”到我们的 ...

  7. WebAPi使用Autofac实现依赖注入

    WebAPi依赖注入  使用记录 笔记 1.NuGet包安装 2.控制器加入构造函数 3.Global.asax  ----Application_Start 应用程序启动时 using Autofa ...

  8. 从零开始搭建.NET Core 2.0 API(学习笔记一)

    从零开始搭建.NET Core 2.0 API(学习笔记一) 一. VS 2017 新建一个项目 选择ASP.NET Core Web应用程序,再选择Web API,选择ASP.NET Core 2. ...

  9. c#实例化继承类,必须对被继承类的程序集做引用 .net core Redis分布式缓存客户端实现逻辑分析及示例demo 数据库笔记之索引和事务 centos 7下安装python 3.6笔记 你大波哥~ C#开源框架(转载) JSON C# Class Generator ---由json字符串生成C#实体类的工具

    c#实例化继承类,必须对被继承类的程序集做引用   0x00 问题 类型“Model.NewModel”在未被引用的程序集中定义.必须添加对程序集“Model, Version=1.0.0.0, Cu ...

随机推荐

  1. 【转】实战Nginx与PHP(FastCGI)的安装、配置与优化

    原文连接:http://ixdba.blog.51cto.com/2895551/806622 原文作者:南非蚂蚁 转载注明以上信息 一.什么是 FastCGIFastCGI是一个可伸缩地.高速地在H ...

  2. socket浅谈

    1什么是socket? socket的英文原义是“孔”或“插座”.作为进程通信机制,取后一种意思. 通常也称作“套接字”,用于描述IP地址和端口,是一个通信链的句柄. (其实就是两个程序通信用的.)是 ...

  3. gcc的stdcall扩展

    MSVC上: 如果是函数调用约定直接就写 __stdcall 之类的就行了 如果是gcc上: 函数的扩展调用约定要这样写 __attribute__((__stdcall__)),默认为__attri ...

  4. form-validation-engine中的正则表达式

    form-validation-engine是一个不错的表单验证,可以玩玩. (function($) { $.fn.validationEngineLanguage = function() {}; ...

  5. Linux下程序崩溃,ulimit,coredump,gdbserver

    操作系统:Ubuntu10.04 前言:    在程序崩溃后,如何快速定位问题.    以下方法适用于开发调试阶段,不太适用成品.    本文着眼于嵌入式,PC方面更简单.    核心:gdbserv ...

  6. zedboard--Opencv的移植(十)

    今天终于把Opencv的移植搞定了,花了一天的时间,主要是参考了书上和rainysky的博客.下载的2.3.1的版本 第一步肯定是下载opencv的源码包了,在opencv的官网上下载http://s ...

  7. Android手机APN设置(中国移动 联通3G 电信天翼),解决不能上网的问题

    中国移动 第一步,设置CMNET上网 新建APN 1.名称:cmnet 2.APN:cmnet 3.APN类型:default 就仅仅填写上面3个选项,其它都是默认,不用填写. 第二步,设置彩信 新建 ...

  8. Linux FTP安装与简单配置

    1.检測是否原有启动 ps -ef|grep vsftpd 2.检測是否有安装包 rpm -qa|grep vsftpd 3.假设有输出.查看状态并启动 service vsftp status  - ...

  9. libaio under MIPS architecture /在mips架构下使用的libaio

    First, you can find libaio source in http://libaio.sourcearchive.com/ Second,download the libaio_0.3 ...

  10. python 笔记3--高级特性

    切片 语法 L[l:r] 取L[l],L[l+1]-L[r-2],L[r-1] L[l:r:m] 取L[l],L[l+m],L[l+2*m],L[l+3*m]-.(满足l+n*m<=r-1) t ...