Autofac在 Asp.net WebAPi中的简单使用

Autofac在 Asp.net WebAPi中的使用

1 新建Web Api 项目, 结构如图

通过Nuget添加 Autofac和 Autofac.WebApi2 package

2 在App_Start文件夹下新建AutofacConfig类,用来配置Autofac,代码如下

    public class AutofacConfig
    {
        /// <summary>
        /// Registes the service.
        /// </summary>
        public static void RegisteService()
        {
            ContainerBuilder builder = new ContainerBuilder();

            string dbType = ConfigurationManager.AppSettings["DbType"];
            if (dbType == "SqlServer")
            {
                builder.RegisterType<SqlServerService>().As<IDBService>();
            }
            else
            {
                builder.RegisterType<MySqlService>().As<IDBService>();
            }
            
            //这一句必须要写,否则会出现Controller没有无参构造函数的错误 ......
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            IContainer container = builder.Build();

            // mvc 使用  DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
    }

紧接着在Global.asax文件中新增Autofac的注册,完整代码如下

   protected void Application_Start()
   {
      GlobalConfiguration.Configure(WebApiConfig.Register);

      //注册Autofac 
      AutofacConfig.RegisteService();
   }
   

3 在Controller文件夹下新增一个Controller,完整代码如下

public class HomeController : ApiController
{
    /// <summary>
    /// The database service
    /// </summary>
    private readonly IDBService dbService;

    /// <summary>
    /// Initializes a new instance of the <see cref="HomeController"/> class.
    /// </summary>
    /// <param name="dbService">The database service.</param>
    public HomeController(IDBService dbService)
    {
        this.dbService = dbService;
    }

    /// <summary>
    /// 测试Autofac和Swagger
    /// </summary>
    /// <returns>Task&lt;IHttpActionResult&gt;.</returns>
    [HttpGet]
    public async Task<IHttpActionResult> Index()
    {
        string serviceName = this.dbService.GetServiceName();
        return this.Ok(await Task.FromResult(serviceName));
    }
}

4 运行,在浏览器中输入http://localhost:23626/api/home 结果如下

posted @ 2017-10-23 14:33  水目之痕  阅读(523)  评论(0编辑  收藏  举报