应用程序设置c#的依赖注入实现

时间:2017-06-15 11:34:49

标签: c# dependency-injection

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依赖注入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

想要实现依赖注入 -

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

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

1 个答案:

答案 0 :(得分: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;
    }

始终使用接口进行依赖注入。