第一次在MVC 5 + Web Api 2的模板中配置Autofac,记录备查。
Solution的结构是:
使用Web API模板创建的MVC 5和Web API2的主项目,然后将Controller单独分离出去成为一个Controller项目。
然后添加一个接口定义的Interface项目以及一个业务层Business项目。
在Interface项目中定义接口,然后Business项目中继承接口实现逻辑,最后在Controller项目中使用接口。
Autofac的配置方法:
1,主项目中引用Autofac 3.5, Autofac.Integration.Mvc 3.3,Autofac.Integration.WebApi 3.4这三个程序集,注意最后一个的版本是3.4,在Nuget中搜索Autofac.webapi2可以找到。
2,在分离出去的Controller项目中引用Autofac 3.5和Autofac.Integration.Mvc 3.3 这两个程序集
然后在主项目的Application_Start()方法中添加如下代码配置Autofac:
var builder = new ContainerBuilder();
string ControllerDllNS = "Demo.MyController"; //Controller程序集命名空间
string BusinessDllNS = "Demo.MyBusiness"; //业务逻辑程序集命名空间
var controllerDll = Assembly.Load(ControllerDllNS);
var businessDll = Assembly.Load(BusinessDllNS);
builder.RegisterControllers(controllerDll);
builder.RegisterApiControllers(controllerDll);
builder.RegisterAssemblyTypes(controllerDll).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(businessDll).AsImplementedInterfaces();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
配置好之后,在interface项目中定义一个接口:
public interface IOutput
{
string Write(string message);
}
在business项目中实现这个接口:
public class Output : IOutput
{
public string Write(string message)
{
return message;
}
}
最后在Controller中使用IOutput:
public class OutputController : ApiController
{
private IOutput writer;
public OutputController(IOutput writer)
{
this.writer = writer;
}
[HttpGet]
public string Write(string msg)
{
return this.demo.Write(msg);
}
}