webapi框架搭建-依赖注入之autofac

webapi框架搭建系列博客

前言

  c#的依赖注入框架有unity、autofac,两个博主都用过,感觉unity比较简单而autofac的功能相对更丰富(自然也更复杂一点),本篇将基于前几篇已经创建好的webapi项目,引入autofac功能。

  前面我们已经搭建好webapi,并用了owin技术。这篇的autofac也将基于这两种技术进行开发。

步骤

引入包

共三个nuget包:Autofac.WebApi2,Autofac.Owin, Autofac.WebApi2.Owin 
 
autofac注册组件
 
using System.Reflection;
using Autofac;
using Autofac.Integration.WebApi;
using webapi.example;

namespace webapi.AutoFac
{
    public static class ContainerBuilerCommon
    {
        public static IContainer GetWebApiContainer()
        {
            var builder = new ContainerBuilder();
       // 注册webapi的所有控制器 builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
       // 注册一个用于测试的组件。 builder.RegisterType<Chinese>().As<People>(); return builder.Build(); } } }

  除了builder.RegisterApiControllers(Assembly.GetExecutingAssembly())是注册webapi控制器,其它所有的代码都是autofac本身的用法。

  autofac的用法可总结为三步:

    1、创建container builder      

      var builder = new ContainerBuilder();    

    2、注册组件

      autofac怎么注册组件可以参考官网:http://autofac.readthedocs.io/en/latest/register/registration.html

    3、生成依赖注入容器(如果是webapi则将容器传给webapi的DependencyResolver对象)      

      config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

  

用于测试的people接口和两个接口的实现类如下

  public interface People
    {
        string Language();
    }

    public class Chinese : People
    {
        public string Language()
        {
            return "汉语";
        }
    }

    public class American:People
    {
        public string Language()
        {
            return "english";
        }
    }

  

owin管道配置

 public class Startup
    {
        /// <summary>
        /// owin的http请求管道配置函数
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            #region 写在前面的配置
            // 获取webapi的配置
            var config = WebApiConfig.OwinWebApiConfiguration(new HttpConfiguration());
            // 获取webapi的依赖注入容器
            var container = ContainerBuilerCommon.GetWebApiContainer();
            // 配置webapi的依赖注入
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            #endregion

            #region owin组件注册(要注意顺序)
            app.UseAutofacMiddleware(container);// 先注册autofac组件,需要依赖注入功能的组件在此后注册
            app.UseAutofacWebApi(config);//注册AutofacWebApi组件后再注册WebApi组件
            app.UseWebApi(config);
            #endregion
        }

  WebApiConfig类代码如下(非核心代码)

using System.Web.Http;

namespace webapi.Configs
{
    /// <summary>
    /// webapi 配置类
    /// </summary>
    public static class WebApiConfig
    {
        
        /// <summary>
        /// 返回webapi的httpconfiguration配置
        /// 用于webapi应用于owin技术时使用
        /// </summary>
        /// <returns></returns>
        public static HttpConfiguration OwinWebApiConfiguration(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();//开启属性路由
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            return config;
        }
    }
}

  

测试依赖注入是否正常

 创建IOCTestController控制器

/// <summary>
/// 本代码用来测试依赖注入是否正常
/// </summary>
namespace webapi.example
{
    public class IOCTestController : ApiController
    {
        private People _people;
        public IOCTestController(People people)
        {
            _people = people;
        }

        public IHttpActionResult GetLanguage()
        {
            return Ok(_people.Language());
        }
    }
}

  注意:控制器里的_people没有用new的方法去创建,而是交给了控制器的构造函数,并且控制器的创建已经配置成由autofac进行依赖注入,如下代码

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

   所以autofac会在创建IOCTestController时用Chinese代替接口people

            builder.RegisterType<Chinese>().As<People>();

 测试结果如下:

转载于:https://www.cnblogs.com/shengyu-kmust/p/8268654.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值