当前位置: 首页 > 编程语言 > C#

C#使用Autofac批量接口注入依赖总结分享

时间:2023-04-10 22:21:06 C#

背景:  在大佬的Colder框架中看到这个接口注入,然后想学习一下ioc思想和di设计模型。这种写法给我的感觉是非常的清雅,典雅,隽永。关于接口注入,最后推荐的地址是什么。废话少说,走吧。安装:  打开nuget管理工具,安装下面所有红色标记的包(注意:不要装错,按照名字安装)  使用:  我们新建一个DI文件夹,在文件夹中添加接口:IDependency.csnamespaceColdairarrow{///

///注入标记///publicinterfaceIDependency{}}    别问后面会解释.背后    :其实。.这是依赖注入的一个原理。根据这个接口,找到依赖的实现。    建议去这个地址看看:https://www.jb51.net/article/206284.htm    好,继续创建三个类:Student.cs,StudentRepository.cs,和IStudentRepository.cs。StudentRepository.cs中的具体业务可以根据需要修改,这里是为了测试。使用系统;使用System.Collections.Generic;使用System.Linq;使用System.Web;namespaceByzkApi{publicclassStudent{publicintId{get;放;}公共字符串名称{得到;放;}publicstring毕业{get;放;}publicstringSchool{get;放;}publicstringMajor{get;放;}}}使用Coldairarrow;使用系统;使用System.Collections.Generic;使用System.Linq;使用System.Web;命名空间ByzkApi{publicclassStudentRepository:IStudentRepository,IDependency{publicStudentAdd(Studentitem){thrownewNotImplementedException();}publicboolDelete(intid){thrownewNotImplementedException();}publicStudentGet(intid){returnnewStudent(){Name="张三"};}publicIEnumerableGetAll(){thrownewNotImplementedException();}publicboolUpdate(Studentitem){thrownewNotImplementedException();}}}使用系统;使用System.Collections.Generic;使用System.Linq;使用系统文本;使用System.Threading.Tasks;ByzkApi{公共接口IStudentRepository{IEnumerableGetAll();学生获取(intid);学生添加(学生项目);布尔更新(学生项目);布尔删除(intid);StudentRepository实现了两个接口,IStudentRepositoryIDependency(注入标记),最关键的地方,我们打开项目启动的函数Application_Start,然后注入接口依赖使用Autofac;使用Autofac.Extras.DynamicProxy;使用Autofac.Integration.Mvc;使用Autofac.Integration.WebApi;使用ByzkApi.Controllers;使用ByzkApi.Interface;使用Coldairarrow;使用Microsoft.Extensions.DependencyInjection;使用System.Linq;使用System.Reflection;使用System.Web.Compilation;使用System.Web.Http;使用System.Web.Mvc;使用System.Web.Optimization;使用System.Web.Routing;namespaceByzkApi{publicclassWebApiApplication:System.Web.HttpApplication{protectedvoidApplication_Start(){//初始化AutofacInitAutofac(GlobalConfiguration.Configuration);AreaRegistration.RegisterAllAreas();GlobalConfiguration.Configure(WebApiConfig.Register);FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);RouteConfig.RegisterRoutes(RouteTable.Routes);BundleConfig.RegisterBundles(BundleTable.Bundles);}privatevoidInitAutofac(HttpConfigurationconfig){varbuilder=newContainerBuilder();varbaseType=typeof(IDependency);//可以过滤如:Where(x=>x.FullName.Contains("Coldairarrow"))varassemblys=BuildManager.GetReferencedAssemblies().Cast().ToList();//自动注入IDependency接口,支持AOP,生命周期为InstancePerDependencybuilder.RegisterAssemblyTypes(assemblys.ToArray()).Where(x=>baseType.IsAssignableFrom(x)&&x!=baseType).AsImplementedInterfaces().PropertiesAutowired().InstancePerDependency().EnableInterfaceInterceptors().InterceptedBy(typeof(Interceptor));//注册控制器builder.RegisterControllers(assemblys.ToArray()).PropertiesAutowired();建设者。注册ApiControllers(assemblys.ToArray()).PropertiesAutowired();//AOPbuilder.RegisterType();builder.RegisterWebApiFilterProvider(配置);varcontainer=builder.Build();DependencyResolver.SetResolver(newAutofacDependencyResolver(容器));varresolver=newAutofacWebApiDependencyResolver(容器);GlobalConfiguration.Configuration.DependencyResolver=解析器;AutofacHelper.Container=容器;普通Controller也可以用在apiController中,单独看效果,结束    控制器:usingSystem;使用System.Collections.Generic;使用System.Linq;使用System.Web;使用System.Web.Mvc;namespaceByzkApi.Controllers{publicclassHomeController:Controller{readonlyIStudentRepository存储库;控制器注入publicHomeController(IStudentRepositoryrepository){this.repository=repository;}publicActionResultIndex(){vara=repository.Get(1);ViewBag.Title=a.Name;返回视图();}}}  ApiController:(如果要多个接口,实现接口时只需要继承IDependency)usingByzkApi.Interface;使用Coldairarrow.Web;使用系统;使用System.Collections.Generic;使用系统数据;使用系统。林克;使用System.Web;使用System.Web.Http;命名空间ByzkApi.Controllers{公共类TestApiController:ApiController{readonlyIStudentRepository存储库;公共ITest_test{ge吨;}//构造函数注入publicTestApiController(IStudentRepositoryrepository,ITesttest){this.repository=repository;_test=测试;}[HttpGet]publicDataTabletest(stringsql){repository.Get(1);vardata=_test.GetTest("sql语句");//repository.GetTest(sql);返回数据;关于C#使用Autofac批量接口注入依赖的文章到此结束,更多关于C#Autofac批量注入的内容请搜索往期文章或继续浏览下方相关文章。希望以后大家多多支持!本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: