首页 文章

Ninject多个绑定的构造函数参数

提问于
浏览
0

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

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

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

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

2 回答

  • 0

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

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

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

    希望能帮助到你 .

相关问题