环境是 mvc5. Visual Studio 2017.
引用相关程序集
Nuget 搜索 Autofac, 引用前两个 Autofac 和 Autofac.Mvc5 如图
新建测试类
以保存日志为例。新建 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) { } }
|
新建 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());
builder.RegisterType<DbLog>().As<ILog>();
var container = builder.Build(); 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(); } }
|