这篇文章主要介绍了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 { List<UserEntity> GetUsers(); } }
新建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 List<UserEntity> GetUsers() { List<UserEntity> list = new List<UserEntity>() { new UserEntity(){UserId=1,UserName="王五",Sex=2,Age=21}, new UserEntity(){UserId=2,UserName="赵六",Sex=2,Age=23}, }; return list; } } }
新建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 List<UserEntity> GetUsers() { List<UserEntity> list = new List<UserEntity>() { new UserEntity(){UserId=1,UserName="张三",Sex=1,Age=24}, new UserEntity(){UserId=2,UserName="李四",Sex=1,Age=22}, }; return list; } } }
通过NuGet安装所需的依赖项:Autofac、Autofac.WebApi2(如果使用的是WebApi1,这里需要安装WebApi)。
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<SqlServerUserRepository>().As<IUserRepository>().InstancePerRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } }
修改后的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(); } } }
创建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; /// <summary> /// 构造函数中注入 /// </summary> /// <param name="userRepository"></param> public UsersController(IUserRepository userRepository) { this._userRepository = userRepository; } public IHttpActionResult Get() { return Json <List<UserEntity>>( _userRepository.GetUsers()); } } }
启动程序,然后在浏览器里面输入: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<SqlServerUserRepository>().As<IUserRepository>().InstancePerRequest(); // 使用oracle数据库实现 builder.RegisterType<OracleUserRepository>().As<IUserRepository>().InstancePerRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } }
运行结果:
从结果中可以看出:这里使用的是oracle实现的。
新建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<SqlServerUserRepository>().As<IUserRepository>().InstancePerRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } }
注意:
如果是在单独的类库项目中,注册Api控制器的时候要加载WebApi项目所有的程序集文件,不要使用builder.RegisterApiControllers(Assembly.GetExecutingAssembly()),这里找到的当前程序集是类库文件,不是WebApi项目的程序集文件,在控制器里面不会实现注入。
修改后的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实现依赖注入”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。