一、前言

  AutoFac是.NET平台下的一款著名的IoC Container,它可以让我们很轻松的解除项目中服务类的接口与客户类的接口实现类之间的依赖关系,从而降低系统各模块之间耦合程度以提高系统的稳定性。最近在做毕业设计,在开发中采用了autofac来进行依赖注入,这里是对踩到的一些坑的解决方法,希望可以给同样不幸进入这些坑中的童鞋们提供一些解决思路。

  对于IOC、DI相关的概念由于自己也是一知半解的,推荐T2噬菌体的这篇 依赖注入那些事儿 写的很详细也很好理解。

  AutoFac文档地址:http://autofac.readthedocs.io/en/latest/getting-started/index.html

  使用AutoFac需要引用的类库dll:Autofac.dllAutofac.ConfigurationMicrosoft.Extensions.Configuration.Xml

  PS:我是采用xml进行配置的AutoFac,如果你采用json进行配置,则需要引用Microsoft.Extensions.Configuration.Xml,使用nuget即可获取到这些引用dll。

 二、实例

  项目结构如下图所示,autofac涉及到类库如下

  PSU.Factory:autofac配置相关信息

  PSU.Domain:功能接口的实现类

  PSU.IService:功能接口

  PSU.Controllers:控制器

AutoFac - 将 autofac 应用于MVC多层项目

  PSU.IService、PSU.Domain就是基本的接口与其实现类,也就没什么东西了,测试的代码如下:

 1 //-----------------------------------------------------------------------
 2 // <copyright file= "IIndex.cs">
 3 //     Copyright (c) Danvic712. All rights reserved.
 4 // </copyright>
 5 // Author: Danvic712
 6 // Date Created: 2018/1/9 星期二 16:37:48
 7 // Modified by:
 8 // Description: 管理员首页操作邻域
 9 //-----------------------------------------------------------------------
10 using PSU.Models.Area.Administrator.Home;
11 using System;
12 using System.Collections.Generic;
13 using System.Linq;
14 using System.Text;
15 using System.Threading.Tasks;
16 
17 namespace PSU.IService.Area.Administrator.Home
18 {
19     public interface IIndex
20     {
21         /// <summary>
22         /// 页面初始化加载
23         /// </summary>
24         /// <param name="webModel"></param>
25         /// <returns></returns>
26         IndexWebModel Init(IndexWebModel webModel);
27     }
28 }
接口定义

相关文章: