C#-----------IOC依赖注入
(2022-07-04 13:53:26)分类: C# |
https://blog.csdn.net/weixin_30265171/article/details/95780443
【ICO实例】
四、ASP.NET MVC使用Grace的Demo
1 public class DependencyInjectionScope2 { 3 public static DependencyInjectionConta iner GetContainer() 4 { 5 //容器 6 var container = new DependencyInjectionContainer(); 7 container.Configure(m => 8 { 9 //这里演示如何简单注册同一个接口对应其实现 10 m.Export().As(); 11 m.Export().As(); 12 13 //这里演示如何使用键值注册同一个接口的多个实现 14 m.Export().AsKeyed("A"); 15 //这里同时演示使用带参数构造器来键值注册 16 m.Export().AsKeyed("B").WithCtorParam<<span style="box-sizing: border-box; outline: 0px; margin: 0px; padding: 0px; overflow-wrap: break-word; color: rgb(0, 0, 255);">string>(() => { return "kkkkk"; }); 17 18 //这里演示依赖倒置而使用构造器带键值注入 19 m.Export().As().WithCtorParam().LocateWithKey("B"); 20 }); 21 22 return container; 23 } 24 }
1 public class MvcApplication : System.Web.HttpApplication 2 { 3 protected void Application_Start() 4 { 5 AreaRegistration.RegisterAllAreas(); 6 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 7 RouteConfig.RegisterRoutes(RouteTable.Routes); 8 BundleConfig.RegisterBundles(BundleTable.Bundles); 9 10 //获取注册容器 11 var graceIocContainer = DependencyInjectionScope.GetContainer(); 12 //MVC指定Grace的工厂为控制器实例工厂 13 ControllerBuilder.Current.SetControllerFactory(new DisposalScopeControllerActivator(graceIocContainer)); 14 } 15 }
1 public class HomeController : Controller 2 { 3 //IExportLocatorScope可以获取从InjectionScope和LifeTimeScope注入的类型实例 4 IExportLocatorScope locator; 5 6 IAccountRepository accountRepo; 7 IAccountService accountSvc; 8 IUserRepository userRepo; 9 IUserService userSvc; 10 11 public HomeController(IExportLocatorScope locator, IAccountRepository accountRepo, IAccountService accountSvc, IUserService userSvc) 12 { 13 this.locator = locator; 14 //获取简单注册实例 15 this.accountRepo = accountRepo; 16 this.accountSvc = accountSvc; 17 //获取指定键值的实例 18 this.userRepo = this.locator.Locate(withKey: "A"); 19 this.userSvc = userSvc; 20 21 } 22 23 public ActionResult Index() 24 { 25 return Json(new 26 { 27 accountRepoGet = accountRepo.Get(), 28 accountSvcGet = accountSvc.Get(), 29 userRepoGet = userRepo.Get(), 30 userSvcGet = userSvc.Get(), 31 }, JsonRequestBehavior.AllowGet); 32 } 35 }
{ "accountRepoGet": "[Account]简单注册调用[Repo]", "accountSvcGet": "[Account]简单注册调用[Repo][Service]", "userRepoGet": "[User]键值注册调用A[Repo]", "userSvcGet": "[User]键值注册调用B,Ctor param1:kkkkk[Repo][Service]" }
前一篇:微信小程序背景图片
后一篇:vue-插件分享,来自技术胖分享