2017-06-15 68 views
1

NotificationHubConnectionSettings.cs文件使用Unity依賴注入的NuGet設置依賴注入實施應用C#

private static IUnityContainer BuildUnityContainer() 
     { 
      try 
      { 
       var container = new UnityContainer(); 

       container.RegisterType<NotificationHubConnectionSettings>().RegisterType<NotificationHubConnectionSettings>(new HierarchicalLifetimeManager()); 

       return container; 

      } 
      catch (Exception) 
      { 
       return null; 
      } 

     } 

HomeController.cs

要來從web.config中

public class NotificationHubConnectionSettings 
    { 
     public NotificationHubClient Hub { get; set; } 
     public NotificationHubConnectionSettings() 
     { 
      Hub = NotificationHubClient.CreateClientFromConnectionString(ConfigurationManager.AppSettings["Microsoft.Azure.NotificationHubs.ConnectionString"], ConfigurationManager.AppSettings["NotificationHub"]); 
     } 
    } 

Bootstrapper.cs 連接字符串實施依賴注入 -

private readonly NotificationHubClient _hub; 

     public HomeController(NotificationHubConnectionSettings hub) 
     { 
      _hub = hub.Hub; 
     } 

     // POST api/register 
     // This creates a registration id 
     public async Task<string> Post(string handle = null) 
     { 
      string newRegistrationId = null; 

      if (handle != null) 
      { 
       var registrations = await _hub.GetRegistrationsByChannelAsync(handle, 100); 

這是實現依賴注入的正確方法嗎?

+0

這是一個代碼審查問題。這是本網站的主題。有沒有遇到一些錯誤/問題? – Nkosi

+0

它看起來並不適合我,但是我不太瞭解Unity作爲一個容器。您應該將接口綁定到容器代碼中的具體類型。註冊類型()。RegisterType (new HierarchicalLifetimeManager()) 然後,您應該將該接口作爲構造函數參數類型。 –

回答

0

您應該在這裏使用接口類型。

以接口的形式爲INotificationHubConnectionSettings類創建合約,該接口向您的系統指示所有可用的公共方法和屬性。

public interface INotificationHubConnectionSettings 
    { 
     NotificationHubClient Hub { get; set; } 
    } 

然後讓您的實際NotificationHubConnectionSettings類從此接口繼承;

public class NotificationHubConnectionSettings : INotificationHubConnectionSettings 
    { 
     public NotificationHubClient Hub { get; set; } 
     public NotificationHubConnectionSettings() 
     { 
      Hub = NotificationHubClient.CreateClientFromConnectionString(ConfigurationManager.AppSettings["Microsoft.Azure.NotificationHubs.ConnectionString"], ConfigurationManager.AppSettings["NotificationHub"]); 
     } 
    } 

現在在UnityContainer中註冊接口和類並將您的構造函數更改爲以下內容;

private readonly INotificationHubClient _hub; 
    public HomeController(NotificationHubConnectionSettings hub) 
    { 
     _hub = hub.Hub; 
    } 

總是使用接口進行依賴注入。

+0

我們沒有接口'INotificationHubClient' – Nix

+0

我們可以這樣做 'private readonly NotificationHubClient _hub; public BuildingAlertController(INotificationHubConnectionSettings集線器) _hub = hub.Hub; }' – Nix