Web API中如何使用Autofac实现依赖注入
这篇文章主要介绍了Web API中如何使用Autofac实现依赖注入的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Web API中如何使用Autofac实现依赖注入文章都会有所收获,下面我们一起来看看吧。
一、创建实体类库
创建单独实体类
创建DI.Entity类库,用来存放所有的实体类,新建用户实体类,其结构如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace DI.Entity{ public class UserEntity { public int UserId { get; set; } public string UserName { get; set; } public int Sex { get; set; } public int Age { get; set; } }}
二、创建仓储接口类库
新建DI.Interface类库文件,存放所有接口,IUserRepository接口定义如下:
using DI.Entity;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace DI.Interface{ public interface IUserRepository { ListGetUsers(); }}
三、创建仓储接口的实现类库
1、SQL Server数据库实现
新建DI.SqlServer类库文件,SqlServerUserRepository实现IUserRepository接口,SqlServerUserRepository类定义如下:
using DI.Entity;using DI.Interface;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace DI.SqlServer{ public class SqlServerUserRepository : IUserRepository { public ListGetUsers() { List list = new List () { new UserEntity(){UserId=1,UserName="王五",Sex=2,Age=21}, new UserEntity(){UserId=2,UserName="赵六",Sex=2,Age=23}, }; return list; } }}
2、Oracle数据库实现
新建DI.Oracle类库文件,OracleUserRepository实现IUserRepository接口,OracleUserRepository类定义如下:
using DI.Entity;using DI.Interface;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace DI.Oracle{ public class OracleUserRepository : IUserRepository { public ListGetUsers() { List list = new List () { new UserEntity(){UserId=1,UserName="张三",Sex=1,Age=24}, new UserEntity(){UserId=2,UserName="李四",Sex=1,Age=22}, }; return list; } }}
四、新建WebAPI项目
1、安装依赖项
通过NuGet安装所需的依赖项:Autofac、Autofac.WebApi2(如果使用的是WebApi1,这里需要安装WebApi)。
2、创建AutofacWebApiConfig类
AutofacWebApiConfig类定义如下:
using Autofac;using Autofac.Integration.WebApi;using DI.Interface;using DI.SqlServer;using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Web;using System.Web.Http;namespace WebApi.AutofacDI{ public class AutofacWebApiConfig { public static void RegisterDependencies() { SetAutofacWebapi(); } private static void SetAutofacWebapi() { ContainerBuilder builder = new ContainerBuilder(); HttpConfiguration config = GlobalConfiguration.Configuration; // Register API controllers using assembly scanning. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces(); // 使用SQLserver数据库实现 builder.RegisterType().As ().InstancePerRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } }}
3、修改Global.asax文件
修改后的Global.asax文件定义如下:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Http;using System.Web.Mvc;using System.Web.Optimization;using System.Web.Routing;using WebApi.AutofacDI;namespace WebApi{ public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // 配置依赖注入 AutofacWebApiConfig.RegisterDependencies(); } }}
4、创建Users控制器
创建UsersController类,并在构造函数中注入,UsersController类定义如下:
using DI.Entity;using DI.Interface;using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Web.Http;namespace WebApi.Controllers{ public class UsersController : ApiController { private IUserRepository _userRepository; ////// 构造函数中注入 /// /// public UsersController(IUserRepository userRepository) { this._userRepository = userRepository; } public IHttpActionResult Get() { return Json>( _userRepository.GetUsers()); } }}
5、测试
启动程序,然后在浏览器里面输入:http://localhost:51157/api/users,结果如下:
从结果中可以看出:这里使用的是SQLserver实现的。
修改AutofacWebApiConfig文件,用oracle实现,修改后的代码如下:
using Autofac;using Autofac.Integration.WebApi;using DI.Interface;using DI.Oracle;using DI.SqlServer;using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Web;using System.Web.Http;namespace WebApi.AutofacDI{ public class AutofacWebApiConfig { public static void RegisterDependencies() { SetAutofacWebapi(); } private static void SetAutofacWebapi() { ContainerBuilder builder = new ContainerBuilder(); HttpConfiguration config = GlobalConfiguration.Configuration; // Register API controllers using assembly scanning. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces(); // 使用SQLserver数据库实现 //builder.RegisterType().As ().InstancePerRequest(); // 使用oracle数据库实现 builder.RegisterType ().As ().InstancePerRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } }}
运行结果:
从结果中可以看出:这里使用的是oracle实现的。
五、将Autofac的实现放到单独的类库中
新建DI.Server类库,将Autofac的注册单独放在类库中,AutofacWebApiConfig类定义如下:
using Autofac;using Autofac.Integration.WebApi;using DI.Interface;using DI.SqlServer;using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks;using System.Web.Http;using System.Web.Mvc;namespace DI.Server{ public class AutofacWebApiConfig { public static void RegisterDependencies() { SetAutofacWebapi(); } private static void SetAutofacWebapi() { ContainerBuilder builder = new ContainerBuilder(); HttpConfiguration config = GlobalConfiguration.Configuration; // Register API controllers using assembly scanning. builder.RegisterApiControllers(Assembly.LoadFrom(@"F:\Practice\WebAPI\WebApi依赖注入\DI\WebApiDIDemo\WebApi\bin\WebApi.dll")); builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces(); builder.RegisterType().As ().InstancePerRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } }}
注意:
如果是在单独的类库项目中,注册Api控制器的时候要加载WebApi项目所有的程序集文件,不要使用builder.RegisterApiControllers(Assembly.GetExecutingAssembly()),这里找到的当前程序集是类库文件,不是WebApi项目的程序集文件,在控制器里面不会实现注入。
2、修改Global.asax文件
修改后的Global.asax文件定义如下:
using DI.Server;using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Http;using System.Web.Mvc;using System.Web.Optimization;using System.Web.Routing;namespace WebApi{ public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // 配置依赖注入(注意:这里使用的是单独类库里面的AutofacWebApiConfig类) AutofacWebApiConfig.RegisterDependencies(); } }}
运行程序,效果和上面的一样。
关于"Web API中如何使用Autofac实现依赖注入"这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对"Web API中如何使用Autofac实现依赖注入"知识都有一定的了解,大家如果还想学习更多知识,欢迎关注行业资讯频道。