【问题标题】:Ninject constructor arguments for multiple bindings为多个绑定注入构造函数参数
【发布时间】:2017-10-18 22:16:57
【问题描述】:

我有一个用于处理通知的简单类。

public class ApplePushNotifier : IApplePushNotifier
{
    public ApplePushNotifier(
        ILog log, 
        IMessageRepository messageRepository, 
        IUserRepository userRepository, 
        CloudStorageAccount account, 
        string certPath)
    {
        // yadda
    }

    // yadda
}

还有一个简单的 Ninject 绑定,其中包含用于定位本地证书文件的字符串参数:

kernel.Bind<IApplePushNotifier>().To<ApplePushNotifier>()
            .WithConstructorArgument("certPath", 
                System.Web.Hosting.HostingEnvironment.MapPath("~/bin/apns_universal.p12"));

这显然是非常基本的,一切都很好。现在,我为该类添加了第二个接口:

public class ApplePushNotifier : IApplePushNotifier, IMessageProcessor

我可以像这样添加第二个绑定:

kernel.Bind<IMessageProcessor>().To<ApplePushNotifier>()
            .WithConstructorArgument("certPath",
                System.Web.Hosting.HostingEnvironment.MapPath("~/bin/apns_universal.p12"));

这也有效,但是重复的构造函数参数让我很烦。我尝试添加这样的显式自绑定:

        kernel.Bind<ApplePushNotifier>().To<ApplePushNotifier>()
            .WithConstructorArgument("certPath",
                System.Web.Hosting.HostingEnvironment.MapPath("~/bin/apns_universal.p12"));
        kernel.Bind<IApplePushNotifier>().To<ApplePushNotifier>();
        kernel.Bind<IMessageProcessor>().To<ApplePushNotifier>();

但没有骰子 - 我收到旧的“没有可用的匹配绑定”错误。

有没有办法指定这样的构造函数参数,而不将其提升为它自己的可绑定类型,或者为类实现的每个接口重复它?

【问题讨论】:

    标签: c# ninject


    【解决方案1】:

    只需为两个服务接口创建一个绑定:

    kernel.Bind<IApplePushNotifier, IMessageProcessor>().To<ApplePushNotifier>()
        .WithConstructorArgument(
            "certPath", System.Web.Hosting.HostingEnvironment.MapPath("~/bin/apns_universal.p12"))
    

    【讨论】:

    • 几乎太容易了!我知道必须有一种简单的方法来处理这个问题,谢谢!
    【解决方案2】:

    根据 ApplePushNotifier 内部工作的性质,绑定到常量可能会有所帮助,并且可以防止重复。

        kernel.Bind<ApplePushNotifier>().ToSelf()
            .WithConstructorArgument("certPath", System.Web.Hosting.HostingEnvironment.MapPath("~/bin/apns_universal.p12"));
    
        var applePushNotifier = Kernel.Get<ApplePushNotifier>();
    
        kernel.Bind<IApplePushNotifier>().ToConstant(applePushNotifier);
        kernel.Bind<IMessageProcessor>().ToConstant(applePushNotifier);
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 2015-11-11
      相关资源
      最近更新 更多