autofac 註入中i遇到的泛型傳參問題

来源:http://www.cnblogs.com/hfdel/archive/2016/12/08/6145547.html
-Advertisement-
Play Games

之前的代碼 ...


using Autofac;
using IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TT.Service.Interface;
using TT.Service.Realize;

namespace InjectionServer
{
    public class Dependency
    {

        public static Assembly Assemblys { set; get; } = Assembly.Load("TT.Service");

        static Dependency()
        {
            if (Builder == null)
            {
                Builder = new ContainerBuilder();//初始化容器
                Builder.RegisterAssemblyTypes(Assemblys)
                .Where(o => o != typeof(IRepository<>))
                .AsImplementedInterfaces().PropertiesAutowired().InstancePerDependency();
                InstanceContainer = Builder.Build();
            }
        }

        public Dependency()
        {
            var type = this.GetType();
            foreach (var item in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                try
                {
                    string key = "TT.Service.Interface." + $"I{item.Name.Replace("Example", "")}";
                    Type t = Assemblys.GetType(key);
                    var method = type.GetMethod("GetInstance", BindingFlags.Static | BindingFlags.NonPublic)
                                                  .MakeGenericMethod(t);
                    item.SetValue(this, method.Invoke(null, null));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        /// <summary>
        /// 取出對象管理
        /// </summary>
        internal static IContainer InstanceContainer { get; set; }

        /// <summary>
        /// 註冊對象管理
        /// </summary>
        internal static ContainerBuilder Builder { get; set; }

        internal static T GetInstance<T>()
            where T : class
        {
                var instance = InstanceContainer.Resolve<T>();
                return instance;
        }

        internal static void Register<T, K>()
                where T : class
                where K : class
        {
            Builder.RegisterType<T>().As<K>().PropertiesAutowired().InstancePerDependency();
        }

        public IUsers UsersExample { set; get; }

        public ITest TestExample { set; get; }
    }
}

  

 

之前的代碼

 1 using Autofac;
 2 using IService;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Reflection;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using TT.Service.Interface;
10 using TT.Service.Realize;
11 
12 namespace InjectionServer
13 {
14     public class Dependency
15     {
16          static Dependency()
17         {
18             if (Builder == null)
19             {
20                 Builder = new ContainerBuilder();
21                 Register();
22                 InstanceContainer = Builder.Build();
23             }
24         }
25 
26         #region 容器管理
27         /// <summary>
28         /// 取出對象管理
29         /// </summary>
30         internal static IContainer InstanceContainer { get; set; }
31 
32         /// <summary>
33         /// 註冊對象管理
34         /// </summary>
35         internal static ContainerBuilder Builder { get; set; }
36 
37         /// <summary>
38         /// 獲取指定介面的實例
39         /// </summary>
40         /// <typeparam name="T"></typeparam>
41         /// <returns></returns>
42         internal static T GetInstance<T>()
43             where T : class
44         {
45             var instance = InstanceContainer.Resolve<T>();
46             return instance;
47         }
48 
49         /// <summary>
50         /// 註冊並且設置為在一個生命周期域中,每一個依賴或調用創建一個單一的共用的實例,且每一個不同的生命周期域,實例是唯一的,不共用的。
51         /// </summary>
52         /// <typeparam name="T"></typeparam>
53         /// <typeparam name="K"></typeparam>
54         /// <param name="t"></param>
55         /// <param name="k"></param>
56         internal static void Register<T, K>()
57              where T : class
58              where K : class
59         {
60             Builder.RegisterType<T>().As<K>().PropertiesAutowired().InstancePerDependency();
61         }
62         #endregion
63 
64         #region 容器註冊
65         internal static void Register()
66         {
67 
68             
69             Register<UserService, IUserService>();
70             //Register<UserService, IUserService>();
71             //Register<UserService, IUserService>();
72            
73         }
74         #endregion
75        
76         public IUsers UsersExample {  get { return GetInstance<IUsersService>(); } }
77 
78        
79     }
80 }

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • CentOS 6.5 x86_64系統下安裝PHP-5.6.4,並且根據生產環境需要做了一定的配置,比如增加了memcache、memcached和redis的擴展支持,對PHP環境安全做了一定配置等。 ...
  • 記憶體管理單元MMU(memory management unit)的主要功能是虛擬地址(virtual memory addresses)到物理地址(physical addresses)的轉換。除此之外,它還可以實現記憶體保護(memory protection)、緩存控制(cache contro... ...
  • 上次創建了欄目模型,這次主要做欄目的前臺顯示。涉及到數據存儲層、業務邏輯層和Web層。用到了遷移,更新資料庫和註入的一些內容。 一、添加數據存儲層 1、添加Ninesky.DataLibrary(與上次添加方法相同) 在解決方案(Ninesky)上點右鍵->添加->新建項目 選擇.NET Core ... ...
  • 本篇博文介紹了#define條件編譯的用途、用法,並結合具體實例進行說明;本文還說明瞭使用條件編譯時需要註意的事項,以及環境變數(或條件編譯符號)的設置方法。 ...
  • 返回目錄 題目有點意思,大家都知道Dictionary<K,V>不是線程安全的類型,而List<T>是線程安全的嗎?在今天之前大叔沒有去測試過,而就在今天也是一個VIP問我,說在我的代碼中使用了並行,然後為一個List賦值,說的直接一點就是:List元素是全局的,在各個線程里分別去操作它,測試數據是 ...
  • 在項目的web.config文件中添加 <connectionStrings> <add name="SQLConnectionString" connectionString="資料庫連接字元串"/> </connectionStrings> 頁面上使用需要添加命名空間 using System. ...
  • 1.許可權控制使用controller和 action來實現,許可權方式有很多種,最近開發項目使用控制控制器方式實現代碼如下 二.單點登錄方式使用application方式來實現 1.用戶登錄成功後記錄當前信息 2.使用ActionFilter來實現單點登錄,每次點擊控制器都去查詢過濾是否在其它地方登錄 ...
  • 什麼是工作隊列 工作隊列是為了避免等待一些占用大量資源或時間操作的一種處理方式。我們把任務封裝為消息發送到隊列中,消費者在後臺不停的取出任務並且執行。當運行了多個消費者工作進程時,隊列中的任務將會在每個消費者間進行共用。 使用工作隊列的好處就是能夠並行的處理任務。如果隊列中堆積了很多任務,只要添加更... ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...