Autofac是应用于.Net平台的依赖注入(DI,Dependency Injection)容器,具有贴近、契合C#语言的特点!
DAL中有一个userinfoDAL.cs
public class userinfoDAL:IDAL.IUserinfo
{
public string getUserType(int Id) {
if (Id == 1) return "1号首长";
return "政委";
}
}
类库IDAL中对应了一个接口 IUserinfo
public interface IUserinfo
{
string getUserType(int Id);
}
}
建立一个mvc 3项目
public class HomeController : Controller
{
private IDAL.IUserinfo _userinfo;
public HomeController(IDAL.IUserinfo userinfo) {
_userinfo = userinfo;
}
public ActionResult Index()
{
ViewData["message"] = _userinfo.getUserType(1);
return View();
}
}
在mvc3的Global.asax中加入配置的代码
protected void Application_Start()
{
//注入
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces();
builder.RegisterType<userinfoDAL>().As<IUserinfo>().SingleInstance();//单列
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
//注入代码结束
AreaRegistration.RegisterAllAreas();
// 默认情况下对 Entity Framework 使用 LocalDB
Database.DefaultConnectionFactory = new sqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
运行程序即可显示结果如下图(简单测试的结果)
using Autofac.Integration.Mvc;
可以参考到:www.51tietu.net 的实现模式