WebAPI_AutoFac(依赖注入)的简单使用

在这里插入图片描述
控制器:构造函数注入不同类型的实例赋值给其实现的接口类型
在这里插入图片描述

  public class UserController : ApiController
    {
   
        private IPersons person;//接收注入的类型实例

        public UserController(UCer ucer)//构造函数注入
        {
   
            this.person = ucer;
        }
        
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Autofac 进行批量依赖注入时,可以使用 Autofac 的 `RegisterAssemblyTypes` 方法实现。 首先,需要在程序集中标记需要注入的类型,可以使用 `Autofac.Module` 类进行实现。例如: ```csharp using Autofac; public class MyModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<MyService>().As<IMyService>(); builder.RegisterType<MyRepository>().As<IMyRepository>(); // 注册其他需要注入的类型 } } ``` 然后,在 `Global.asax.cs` 文件中,使用 `ContainerBuilder` 类创建容器,并把需要注入的模块注册进去。例如: ```csharp using Autofac; using Autofac.Integration.WebApi; using System.Reflection; using System.Web.Http; public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly()); var container = builder.Build(); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } ``` 这样,就可以实现批量依赖注入了。在需要使用注入的类型时,可以通过构造函数注入或属性注入的方式获取实例。例如: ```csharp public class MyController : ApiController { private readonly IMyService _myService; public MyController(IMyService myService) { _myService = myService; } [HttpGet] public IHttpActionResult MyAction() { // 使用 MyService return Ok(); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值