决心用autofce是为了解决以前一个三层架构项目(DAL+IDAL+BLL)+mvc中,老是在控制器中 new BLL.名称.方法 ,不想出现这个new 实例。
于是先做了小小实验,新建立一个解决方案,
类库
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();
}
}
想测试一下能不能显示几号首长,直接失败出错
也许是不懂写配置代码 Global.cs中
protected void Application_Start()
{
//注入
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AsImplementedInterfaces();
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);
}
运行后错误是
None of the constructors found with 'Public binding flags' on type 'WEB.Controllers.HomeController' can be invoked with the available services and parameters:
Cannot resolve parameter 'IDAL.IUserinfo userinfo' of constructor 'Void .ctor(IDAL.IUserinfo)'.
加入
builder.RegisterType<DAL.userinfoDAL>().As<IDAL.IUserinfo>();
恩, 能否设置成了DAL的 全部 AS 为 IDAL,让它自实现而不是一个类要写一行AS?
@我和娜娜:
没有那么智能吧 只能一行行指明