扩大
缩小

.net mvc web api Autofac依赖注入框架-戈多编程

今天自己搭了一套基于三层的依赖注入mvc web api 的依赖注入框架,在此总结下相关配置

1.设置应用程序的.net Framework版本为 4.5

2.通过Nuget 安装autofac包

Install-Package Autofac

Install-Package Autofac.WebApi

3.引用如下命名空间

using Autofac;
using Autofac.Integration.WebApi;
using Autofac.Integration.Mvc;
using System.Web.Mvc;

4.再按照如下代码配置Autofac(分别搭建DAL、BLL、IDAL、IBLL)

public static void Register()
{
var builder = new ContainerBuilder();
HttpConfiguration configuration = GlobalConfiguration.Configuration;
var assemblyList = AppDomain.CurrentDomain.GetAssemblies();


builder.RegisterWebApiFilterProvider(configuration);




//var iServices = Assembly.Load("IOC.IBLL");
//var services = Assembly.Load("IOC.BLL");
//var iRepository = Assembly.Load("IOC.IDAL");
//var repository = Assembly.Load("IOC.DAL");

//builder.RegisterAssemblyTypes(iServices, services)
// .Where(t => t.Name.EndsWith("Service"))
// .AsImplementedInterfaces();

//var test = builder.RegisterAssemblyTypes(iRepository, repository)
// .Where(t => t.Name.EndsWith("Dal"))
// .AsImplementedInterfaces();


builder.RegisterAssemblyTypes(assemblyList)
.Where(t => t.Name.EndsWith("Service") || t.Name.EndsWith("Dal"))
.AsImplementedInterfaces();

builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); //注册所有controller
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); //注册所有apicontroller

var container = builder.Build();

configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);//注册api容器
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//注册mvc容器
}

5.在Application_Start里调用 AutofacConfig.Register();

6.然后在每一层采用构造函数依赖注入方式。

 

posted @ 2017-08-15 13:55  戈多编程  阅读(497)  评论(0编辑  收藏  举报