gpt4 book ai didi

c# - 应用设置c#的依赖注入(inject)实现

转载 作者:太空宇宙 更新时间:2023-11-03 15:04:12 31 4
gpt4 key购买 nike

NotificationHubConnectionSettings.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 中使用 Unity 依赖注入(inject) nuget

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

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

return container;

}
catch (Exception)
{
return null;
}

}

HomeController.cs

想实现依赖注入(inject)——

  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);

这是实现依赖注入(inject)的正确方法吗?

最佳答案

你应该在这里使用一个接口(interface)类型。

以接口(interface)的形式为 INotificationHubConnectionSettings 类创建契约(Contract),该接口(interface)向您的系统指示所有可用的公共(public)方法和属性。

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

然后让您的实际 NotificationHubConnectionSettings 类继承自该接口(interface);

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

现在在 UnityContainer 中注册接口(interface)和类,并将构造函数更改为以下内容;

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

始终使用接口(interface)进行依赖注入(inject)。

关于c# - 应用设置c#的依赖注入(inject)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44566471/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com