2013-06-20 31 views
1

我想使用的綁定設在這裏的方法,但有沒有運氣 https://github.com/ninject/ninject.extensions.factory/wiki/Factory-interface https://github.com/ninject/ninject.extensions.factory/wiki/Factory-interface%3A-Referencing-Named-BindingsNinject工廠沒有與公約工作對我來說

請記住,我不是想這樣來做:https://gist.github.com/akimboyko/4593576 相反我試圖使用慣例GetMercedes()意味着

我基本上試圖達到這個:https://gist.github.com/akimboyko/4593576與上述例子中指定的約定。

using Ninject; 
using Ninject.Extensions.Factory; 
using Ninject.Modules; 
using Ninject.Parameters; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Reflection; 
using System.Text; 
using System.Threading.Tasks; 

namespace Test.NinjectFactory 
{ 
    public class Program 
    { 
     public static void Main() 
     { 
      using (var kernel = new StandardKernel(new CarModule())) 
      { 


       var factory = kernel.Get<ICarFactory>(); 
       var mercedes =factory.GetMercedes(); 
       int i = 1; 

      } 
     } 

     public interface ICar 
     { 
      void Drive(); 

     } 

     public class Mercedes : ICar 
     { 
      readonly ICarFactory carFactory; 
      public Mercedes(ICarFactory carFactory) 
      { 
       this.carFactory = carFactory; 
      } 

      public void Drive() 
      { 
       var Mercedes = this.carFactory.GetMercedes(); 
      } 

     } 


     public interface ICarFactory 
     { 
      ICar GetMercedes(); 
     } 

     public class CarModule : NinjectModule 
     { 
      public override void Load() 
      { 
       //https://github.com/ninject/ninject.extensions.factory/wiki/Factory-interface%3A-Referencing-Named-Bindings 
       Kernel.Bind<ICarFactory>().ToFactory(); 
       Bind<ICar>().To<Mercedes>().NamedLikeFactoryMethod<ICarFactory>(x => x.GetMercedes());//doesnt work for me 

      } 
     } 
    } 
} 

回答

1

我發現這裏的anwswer: https://gist.github.com/akimboyko/5338320

看來你需要一個函數來取的結合

public class BaseTypeBindingGenerator<InterfaceType> : IBindingGenerator 
{ 
    public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot) 
    { 
     if (type != null && !type.IsAbstract && type.IsClass && typeof(InterfaceType).IsAssignableFrom(type)) 
     { 
      string.Format("Binds '{0}' to '{1}' as '{2}", type, type.Name, typeof(InterfaceType)).Dump(); 

      yield return bindingRoot.Bind(typeof(InterfaceType)) 
            .To(type) 
            .Named(type.Name) as IBindingWhenInNamedWithOrOnSyntax<object>; 
     } 
    } 
} 
1

我張貼這是一個答案,因爲它是最有可能原因。

工廠擴展使用前綴爲Get的方法作爲標準。通過調用帶有前綴Get和使用NamedLikeFactoryMethod的任何工廠方法,您將遇到問題。例如,GetFordGetMercedesGetNissan。您會注意到,在您提供的鏈接的示例中,該功能稱爲CreateMercedes

改變你的函數名CreateMercedes任何不與Get開始,它應該是罰款。

+0

目標護理是使用慣例,像這樣:HTTPS://github.com /ninject/ninject.extensions.factory/wiki/Factory-interface%3A-Referencing-Named-Bindings 因此,建議可能不是我所期待的。感謝您花時間回覆。 – hidden