AutoFac  mvc和WebAPI  注册Service (接口和实现)

1、准备组件版本:Autofac 3.5.0    Autofac.Integration.Mvc 3.3.0.0  (Install-package  Autofac.Mvc 相应版本)   Autofac.Integration.WebApi 4.0.0.0 (Install-package  Autofac.WebApi 相应版本)

  ***install-package autofac.webapi2 (注意:您的项目中如果使用的是webapi2,此处必须为webapi2而不是webapi,否则在运行时将出现“重写成员“Autofac.Integration.WebApi.AutofacWebApiDependencyResolver.BeginScope()”时违反了继承安全性规则。重写方法的          安全可访问性必须与所重写方法的安全可访问性匹配。”错误。)

2、Global.asax  中代码:

 protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles); // AutoFac 注入初始化
AutoFacBootStrapper.CoreAutoFacInit();
}

3、实现注入类: AutoFacBootStrapper  及实现批量service注入

 public class AutoFacBootStrapper
{
public static void CoreAutoFacInit()
{
var builder = new ContainerBuilder();
HttpConfiguration config = GlobalConfiguration.Configuration;
//注册所有的Controllers
builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
#region 可正常 用
var baseType = typeof(IDependency);
var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList();
var allServices = assemblys.SelectMany(s => s.GetTypes()).Where(p => baseType.IsAssignableFrom(p) && p != baseType);
builder.RegisterAssemblyTypes(assemblys.ToArray()).Where(t => baseType.IsAssignableFrom(t) && t != baseType)
.AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
//注册所有的ApiControllers
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
//autofac 注册依赖
IContainer container = builder.Build();
// webApi部分注册
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
#endregion 可正常用
} }

4、接口部分需继承 IDpendncy,该类无实现类 仅为批量注册提供标示

 public interface IDependency
{ }

5、IService 和Servicep 实现

 public interface ICustomerService:IDependency
{ string GetCustomerName(); }
 public class CustomerService: ICustomerService
{
/// <summary>
/// 获取客户信息
/// </summary>
/// <returns></returns>
public string GetCustomerName()
{
return "WebAPI_Success";
}
}

6、Controller 调用注入类 和ApiController 调用注入类

  public class HomeController : Controller
{ public ICustomerService _customerService { get; set; }
public ActionResult Index()
{
ViewBag.Title = "Home Page"; return View();
}
}
  public class CustController : ApiController
{ public ICustomerService _customerService { get; set; }
// GET: api/Cust
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
} // GET: api/Cust/5
public string Get(int id)
{
return "value";
} // POST: api/Cust
public void Post([FromBody]string value)
{
}
}

至此Autofac 注入就完成了,如有问题请联系我 相互交流。qq:626382542

AutoFac mvc和WebAPI 注册Service (接口和实现)的更多相关文章

  1. Autofac - MVC/WebApi中的应用

    Autofac前面写了那么多篇, 其实就是为了今天这一篇, Autofac在MVC和WebApi中的应用. 一.目录结构 先看一下我的目录结构吧, 搭了个非常简单的架构, IOC(web), IBLL ...

  2. autofac解析Mvc和Webapi的坑

    我们在项目中很早就开始使用autofac,也以为知道与mvc和webapi集成的做法. var builder = new ContainerBuilder(); // Mvc Register bu ...

  3. 转:autofac在mvc和webapi集成的做法

    本文转自:http://www.cnblogs.com/Hai--D/p/5992573.html var builder = new ContainerBuilder(); // Mvc Regis ...

  4. .net core 源码解析-mvc route的注册,激活,调用流程(三)

    .net core mvc route的注册,激活,调用流程 mvc的入口是route,当前请求的url匹配到合适的route之后,mvc根据route所指定的controller和action激活c ...

  5. mvc route的注册,激活,调用流程

    mvc route的注册,激活,调用流程(三) net core mvc route的注册,激活,调用流程 mvc的入口是route,当前请求的url匹配到合适的route之后,mvc根据route所 ...

  6. 给Asp.Net MVC及WebApi添加路由优先级

    一.为什么需要路由优先级 大家都知道我们在Asp.Net MVC项目或WebApi项目中注册路由是没有优先级的,当项目比较大.或有多个区域.或多个Web项目.或采用插件式框架开发时,我们的路由注册很可 ...

  7. SlickOne -- 基于Dapper, Mvc和WebAPI 的快速开发框架

    前言:在两年前,项目组推出了基于Dapper,Mvc和WebApi的快速开发框架,随着后续Slickflow产品的实践和应用,今再次对SlickOne项目做以回顾和总结.其目的是精简,持续改进,保持重 ...

  8. jsp-3 简单的servlet连接mysql数据库 使用mvc的登录注册

    简单的servlet连接mysql数据库 使用mvc的登录注册 commons-dbutils-1.6 mysql-connector-java-5.1.40-bin c3p0-0.9.5.2 mch ...

  9. C# MVC+EF—WebApi

    上一篇搭建了页面,这里写下功能. 这里我用WebApi实现数据的增删改查. 一.新建Controller 为了区分明确,我在Controller文件夹下建立一个WebApi文件夹存放. 选中文件夹右键 ...

随机推荐

  1. Spring 使用@Async出现循环依赖Bean报错的解决方案

    初现端倪 Caused by:org.springframework.beans.factory.BeanCurrentlyInCreationException: Errorcreating bea ...

  2. 推荐MarkDown编辑工具Typora--文本画流程图示例

    程序员界名言:talk is cheap, show me the code CODE: ### 8. 修改预留手机号-per.MCReservedMobilePhoneUpd #### 8.1业务规 ...

  3. 嵌套循环结合修改IFS环境变量遍历文件数据中IFS的修改一致性

    以下这个脚本使用了两个不同的IFS值来解析数据.第一个IFS值解析出/etc/passwd文件中的单独的行.内部for循环接着将IFS值改为冒号,云溪你从/etc/passwd的行中解析出单独的值. ...

  4. spring_AOP的注解开发

    logger日志类: package cn.mepu.utils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.la ...

  5. JNI原理与静态、动态注册

    前言 JNI不仅仅在NDK开发中应用,它更是Android系统中Java与Native交互的桥梁,不理解JNI的话,你就只能停留在Java Framework层.这一个系列我们来一起深入学习JNI. ...

  6. segment fault 定位 与 远程 gdb

    远程 GDB  首先 ,Target 为 ARM开发板 (IP =  192.168.1.200),HOST 为 Ubuntu 14.04 虚拟机 (IP = 192.168.1.4) 1. 下载  ...

  7. 每天一个Linux常用命令 cp命令

    Linux cp命令主要用于复制文件或目录 -a:此选项通常在复制目录时使用,它保留链接.文件属性,并复制目录下的所有内容.其作用等于dpR参数组合. -d:复制时保留链接.这里所说的链接相当于Win ...

  8. nodejs模块——fs模块 WriteFile写入文件

    WriteFile写入文件 使用fs.writeFile(filename,data,[options],callback)写入内容到文件. 参数说明: filename String 文件名 dat ...

  9. Python排序功能进阶

    sorted和sort() li = [9, 1, 8, 2, 7, 3, 6, 4, 5] s_li = sorted(li) print ('Sorted Variable: \t', s_li) ...

  10. 搭建基于Linux6.3+Nginx1.2+PHP5+MySQL5.5的Web服务器全过程

    http://blog.chinaunix.net/uid-20639775-id-154497.html