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);
這是實現依賴注入的正確方法嗎?
這是一個代碼審查問題。這是本網站的主題。有沒有遇到一些錯誤/問題? – Nkosi
它看起來並不適合我,但是我不太瞭解Unity作爲一個容器。您應該將接口綁定到容器代碼中的具體類型。註冊類型()。RegisterType (new HierarchicalLifetimeManager()) 然後,您應該將該接口作爲構造函數參數類型。 –