AutoMapper: Mapper.Initialize() 只能調用一次,Why?


最開始的代碼

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Reflection;
 7 
 8 using AutoMapper;
 9 
10 using Happy.ExtentionMethods;
11 using Happy.Bootstrap;
12 
13 namespace Happy.Bootstrap.AutoMapper
14 {
15     /// <summary>
16     /// 自動添加配置。
17     /// </summary>
18     public class AutoAddProfilePlugin : IBootstrapPlugin
19     {
20         /// <inheritdoc />
21         public void Start(IBootstrapService bootstrapService, Assembly assembly)
22         {
23             bootstrapService.MustNotNull("bootstrapService");
24             assembly.MustNotNull("assembly");
25 
26             foreach (var type in assembly.GetTypes())
27             {
28                 if (type.IsAbstract || type.IsInterface)
29                 {
30                     continue;
31                 }
32 
33                 if (typeof(Profile).IsAssignableFrom(type))
34                 {
35                     Mapper.Initialize(x => {
36                         x.AddProfile(Activator.CreateInstance(type) as Profile);
37                     });
38                 }
39             }
40         }
41     }
42 }

問題

我的項目中,每個 dll 都是自描述的,系統啟動的時候,對每個 dll 對執行上面的插件,結果, Mapper.Initialize() 只有最后一次配置才有效,前面的配置會丟失。

最后的代碼

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Reflection;
 7 
 8 using AutoMapper;
 9 
10 using Happy.ExtentionMethods;
11 using Happy.Bootstrap;
12 
13 namespace Happy.Bootstrap.AutoMapper
14 {
15     /// <summary>
16     /// 自動添加配置。
17     /// </summary>
18     public class AutoAddProfilePlugin : IBootstrapPlugin
19     {
20         /// <inheritdoc />
21         public void Start(IBootstrapService bootstrapService, Assembly assembly)
22         {
23             bootstrapService.MustNotNull("bootstrapService");
24             assembly.MustNotNull("assembly");
25 
26             foreach (var type in assembly.GetTypes())
27             {
28                 if (type.IsAbstract || type.IsInterface)
29                 {
30                     continue;
31                 }
32 
33                 if (typeof(Profile).IsAssignableFrom(type))
34                 {
35                     Mapper.AddProfile(Activator.CreateInstance(type) as Profile);
36                 }
37             }
38         }
39     }
40 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM