环境是 mvc5. Visual Studio 2017.

引用相关程序集

Nuget 搜索 Autofac, 引用前两个 Autofac 和 Autofac.Mvc5 如图 Nuget

新建测试类

以保存日志为例。新建 ILog.cs 和 DbLog.cs

1
2
3
4
5
6
7
8
9
10
11
12
public interface ILog
{
void Save(string message);
}

public class DbLog : ILog
{
public void Save(string message)
{
//TODO.链接数据库 保存日志
}
}

新建 Autofac.config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class AutofacConfig
{
public static void Register()
{
ContainerBuilder builder = new ContainerBuilder();
//注册控制器
builder.RegisterControllers(Assembly.GetExecutingAssembly());
//TODO.在这注册

//注册日志测试类
builder.RegisterType<DbLog>().As<ILog>();


var container = builder.Build();
//移交Mvc
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

}

Controller 中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class HomeController : Controller
{
private readonly ILog _log;

public HomeController(ILog log)
{
this._log = log;
}


public ActionResult Index()
{
_log.Save("Home.Index");
return View();
}
}