首先,推荐使用Visual Studio 2010 中的NuGet 组件,在MVC 项目中,来安装和添加对Autofac ASP.NET MVC3 Integration 组件的引用,具体操作可参考《使用NuGet 来管理Visual Studio的开源组件(Package)》。
在上述步骤完成之后,在项目的Global.asax文件中,实施对Controller的依赖注入。
在Global.asax中,需要添加如下2个命名空间的引用:
1
2
3
|
using
Autofac;
using
Autofac.Integration.Mvc;
|
在Application_Start() 方法中添加如下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
protected
void
Application_Start()
{
var builder =
new
ContainerBuilder();
SetupResolveRules(builder);
// use a provided extension method to register all the controllers in an assembly
builder.RegisterControllers(Assembly.GetExecutingAssembly());
// create a new container with the component registrations
IContainer container = builder.Build();
// use the static DependencyResolver.SetResolver method
// to let ASP.NET MVC know that it should locate services
// using the AutofacDependencyResolver
DependencyResolver.SetResolver(
new
AutofacDependencyResolver(container));
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
|
其中SetupResolveRules() 是我们自定义的方法,用来建立Interface和Class之间的关联,代码如下:
1
2
3
4
5
6
7
8
9
10
11
|
private
void
SetupResolveRules(ContainerBuilder builder)
{
//Components are wired to services using the As() methods on ContainerBuilder
builder.RegisterType<MessageRepository>().As<IMessageRepository>();
builder.RegisterType<MemberRepository>().As<IMemberRepository>();
}
|
不过,如果项目中有比较多的Interface 和Class需要建立关联,则需要逐条在上述方面中添加。这样,增加了后期的一些维护工作。
下面提供了另外一种方法,将当前运行的Assembly中所有以Repository结尾的Class 和其所实现的Interface进行关联。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
private
void
SetupResolveRules(ContainerBuilder builder)
{
// Speficy that a type from a scanned assembly is registered
// as providing all of its implementation interfaces.
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.Name.EndsWith(
"Repository"
))
.AsImplementedInterfaces();
}
|
上述代码的范例程序(ASP.NET MVC 3 + Autofac)下载地址:
http://download.csdn.net/source/3234339
范例程序的运行界面如下:
相关文档,可参考如下链接:
- Integrating with ASP.NET MVC 3.0,http://code.google.com/p/autofac/wiki/Mvc3Integration
- ASP.NET MVC 2 开发实战
- IoC 容器 — Autofac,http://www.entlib.net/?p=23
所有评论(0)