2017-10-18 62 views
0

Ninject构造函数参数我有一个简单的类我使用的处理通知。的多个绑定

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

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

有没有办法指定一个构造函数的参数像这样没有,要么推动到可绑定类型它自己的,或重复它是类实现的每个接口?

回答

0

只要创建只由一个服务的接口绑定:

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

简直太容易了!我知道必须有一个简单的方法来处理这个问题,谢谢! – superstator

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

希望它能帮助。