Reference AutoFac assembly
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using DotNET_MvcPJ.BLL;
using DotNET_MvcPJ.IDAL;
using DotNET_MvcPJ.IServices;
using DotNET_MvcPJ.Repository;
namespace DotNET_MvcPJ.Main.App_Start
{
/// <summary>
/// AutoFac配置文件
/// </summary>
public class AutoFacConfig
{
/// <summary>
/// 注册配置
/// </summary>
public static void Register()
{
//1.创建(实例化一个)AutoFac容器对象
var build = new ContainerBuilder();
//2.获取程序集加载到Assembly对象中
Assembly assembly = Assembly.Load("DotNET_MvcPJ.Main");
//3.告诉AutoFac对象来实例化控制器所在的程序集是DotNET_MvcPJ.Main
//默认控制器初始化器(DefaultControllerFactory)会自动调用无参构造函数,因为我们使用了构造函数注入,所以会找不到无参构造函数,会报错,所以要把创建权交给AutoFac来实例化
build.RegisterControllers(assembly);
#region 仓储层注册
//4.利用Build对象开始创建仓储的实现类与对应的仓储接口的对应关系
//注意:如果加了InstanceperHttpRequest()每次都是新的实体进行注入操作
//注册当个仓储来到其对应的接口
//build.RegisterType(typeof(studentInfoDal)).As(typeof(IstudentInfoDal));
//注册程序中所有的类到其实现的接口
Assembly dalAser = Assembly.Load("DotNET_MvcPJ.Repository");
build.RegisterTypes(dalAser.GetTypes()).AsImplementedInterfaces();
#endregion
#region 业务逻辑层的注册
//5.利用Build对象开始创建业务逻辑实现类与对应的业务逻辑接口的对象关系
//单个注册业务逻辑类到其实现接口
//build.RegisterType(typeof(studentInfoService)).As(typeof(IstudentInfoService)).InstancePerHttpRequest();
//注册业务逻辑层中所有的类到其实现的接口 (AsImplementedInterfaces() 此方法:就是用来自动转成接口的)
Assembly serviecsDll = Assembly.Load("DotNET_MvcPJ.BLL");
build.RegisterTypes(serviecsDll.GetTypes()).AsImplementedInterfaces();
//注册当前程序中类型名称的前缀为SysTemSchool 的所有对应类的实例
//build.RegisterTypes(serviecsDll.GetTypes().Where(u => u.Name.StartsWith("SysTemSchool")).ToArray()).AsImplementedInterfaces();
#endregion
//6.告诉MVC框架将来所有的控制器对象的创建工作交给AutoFac中的控制器工厂来完成
//特点:会利用控制器中的所有有参构造函数创建其对象,同时在创建中会根据其构造函数中的接口参数
//将此接口的具体实现类的对象注入
//6.1 根据已经注册号的组件创建此容器对象中所有的映射关系的具体实现
var container = build.Build();
//6.2 将MVC的控制器对象实例的创建交给AutoFac来创建,不再使用默认控制器工厂来初始化
//参数是autofac容器(用来创建控制器对象,初始化整个项目文件)
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
}
Business logic
Controller
project files
The main project file references Entity Framework
Copy the ConnectionString link string of the Model layer and add it to Web.Config
Run the test.
Register a single implementation class to the interface (for business needs, convert the implementation class)
there must be a corresponding registered assembly in the Bin directory of the main project file (modify the class library generation path)