转载:https://www.cnblogs.com/Insist-Y/p/15272345.html
1.在“工具”->“NuGet包管理器”->"程序包管理器控制台"执行一下代码,安装autofac。
Install-Package Autofac
当使用 autoFac 开发ASP .net 遇到 ContainerBuilder() 不包含RegisterControllers 方法解决方案(MVC环境下,注入Controller需要安装包)
Install-Package Autofac.Mvc5 -Version 4.0.2
当然也可以在项目点击右键点击“管理NuGet程序包 ”,在NuGet管理包页面,搜索AutoFac,进行下载安装。
2.using AutoFac;
using AutoFac.Intergation.MVC;
3.依赖注入配置代码(Golbal.asax的Application_Start方法中添加一下代码)
/// <summary>
/// 使用AutoFac实现依赖注入
/// </summary>
private void autoFac()
{
var builder = new ContainerBuilder();
SetupResolveRules(builder); //注入
builder.RegisterControllers(Assembly.GetExecutingAssembly()); //注入所有Controller
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
private void SetupResolveRules(ContainerBuilder builder)
{
//不推荐下面这种,加载太耗时间,建议使用 AppDomain.CurrentDomain.GetAssemblies();
//UI项目只用引用service和repository的接口,不用引用实现的dll。
//如需加载实现的程序集,将dll拷贝到bin目录下即可,不用引用dll
var IServices = Assembly.Load("MyMVC3.Business.IServices");
var Services = Assembly.Load("MyMVC3.Business.Services");
var IRepository = Assembly.Load("MyMVC3.Modules.IRepository");
var Repository = Assembly.Load("MyMVC3.Modules.Repository");
//根据名称约定(服务层的接口和实现均以Service结尾),实现服务接口和服务实现的依赖
builder.RegisterAssemblyTypes(IServices, Services)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();
//根据名称约定(数据访问层的接口和实现均以Repository结尾),实现数据访问接口和数据访问实现的依赖
builder.RegisterAssemblyTypes(IRepository, Repository)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
}
4.各层之间注入代码
private IUserInfoRepository productRepository;
public UserInfoService(IUserInfoRepository productRepository)
{
this.productRepository = productRepository;
this.AddDisposableObject(productRepository);
}
public IUserInfoService userService;
public HomeController(IUserInfoService userService)
{
this.userService = userService;
this.AddDisposableObject(userService);
}
————————————————
版权声明:本文为CSDN博主「gaozhigang」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/gaozhigang/article/details/80618585