MVC 5 + Web API 2 配置使用Autofac

第一次在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);
        }
    }


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值