码迷,mamicode.com
首页 > 编程语言 > 详细

ASP.NET Core中使用Unity5

时间:2020-05-23 09:26:21      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:set   技术   sys   gif   ade   resolve   gen   word   new   

原文:ASP.NET Core中使用Unity5

⒈添加相关依赖

Install-Package Unity
Install-Package Unity.RegistrationByConvention

⒉扫描项目接口实现类 

技术图片
 1 using System;
 2 using System.Linq;
 3 using Unity;
 4 using Unity.RegistrationByConvention;
 5 
 6 namespace Unity_Test.Unity
 7 {
 8     public class UnityConfig
 9     {
10         private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
11         {
12             var container = new UnityContainer();
13             RegisterTypes(container);
14             return container;
15         });
16 
17         public static IUnityContainer GetConfiguredContainer()
18         {
19             return container.Value;
20         }
21 
22         public static void RegisterTypes(IUnityContainer container)
23         {
24 
25             var assemblyList = AllClasses.FromLoadedAssemblies().Where(w => w.FullName.Contains("Unity_Test"));
26 
27             container.RegisterTypes(
28                   assemblyList,
29                   WithMappings.FromAllInterfacesInSameAssembly,
30                   WithName.Default,
31                   WithLifetime.PerResolve);
32         }
33     }
34 }
技术图片

⒊代码中注入 

技术图片
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using Unity;
 5 
 6 namespace Unity_Test
 7 {
 8     public class Test
 9     {
10         [Dependency]
11         public IService service { get; set; }
12         public void sysout()
13         {
14             service.sayHello();
15             Console.ReadKey();
16         }
17     }
18 }
技术图片

 

技术图片技术图片技术图片

ASP.NET Core中使用Unity5

标签:set   技术   sys   gif   ade   resolve   gen   word   new   

原文地址:https://www.cnblogs.com/lonelyxmas/p/12940785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!