2015-06-11 56 views
0

當設置我的ninject綁定,我使用的是.ToMethod指定特定的ConnectionStrings特定參數和WhenInjectedInto方法來約束綁定到特定類型:可以使用InInjectedInto爲ninject指定多個參數嗎?

 Bind(Of IDbConnection).ToMethod(Function(context) New OracleConnection(ConnectionStringFactory.GetConnection(DBC.ConnectionStrings.Oracle))).WhenInjectedInto(Of AccountBalancesLookup)() 
     Bind(Of IDbConnection).ToMethod(Function(context) New OracleConnection(ConnectionStringFactory.GetConnection(DBC.ConnectionStrings.Oracle))).WhenInjectedInto(Of MFUtility)() 

我的問題是,我可以做像這樣:

 Bind(Of IDbConnection).ToMethod(Function(context) New OracleConnection(ConnectionStringFactory.GetConnection(DBC.ConnectionStrings.Oracle))).WhenInjectedInto(Of AccountBalancesLookup, MFUtility)() 

一次指定多個綁定目標,而不是多行?

回答

1

不開箱即用。但是,您可以創建自己的擴展名爲When(Func<IRequest,bool>),它完全是。例如:

public static class WhenExtensions 
{ 
    public static IBindingInNamedWithOrOnSyntax<T> WhenInjectedInto<T>(
     this IBindingWhenSyntax<T> syntax, params Type[] types) 
    { 
     var conditions = ComputeMatchConditions(syntax, types).ToArray(); 
     return syntax.When(request => conditions.Any(condition => condition(request))); 
    } 

    private static IEnumerable<Func<IRequest, bool>> ComputeMatchConditions<T>(
     IBindingWhenSyntax<T> syntax, Type[] types) 
    { 
     foreach (Type type in types) 
     { 
      syntax.WhenInjectedInto(type); 
      yield return syntax.BindingConfiguration.Condition; 
     } 
    } 
} 

使用,如:

public class Test 
{ 
    [Fact] 
    public void Foo() 
    { 
     var kernel = new StandardKernel(); 

     kernel.Bind<string>().ToConstant("Hello") 
      .WhenInjectedInto(typeof(SomeTypeA), typeof(SomeTypeB)); 

     kernel.Bind<string>().ToConstant("Goodbye") 
      .WhenInjectedInto<SomeTypeC>(); 

     kernel.Get<SomeTypeA>().S.Should().Be("Hello"); 
     kernel.Get<SomeTypeB>().S.Should().Be("Hello"); 

     kernel.Get<SomeTypeC>().S.Should().Be("Goodbye"); 
    } 
} 

public abstract class SomeType 
{ 
    public string S { get; private set; } 

    protected SomeType(string s) 
    { 
     S = s; 
    } 
} 

public class SomeTypeA : SomeType 
{ 
    public SomeTypeA(string s) : base(s) { } 
} 

public class SomeTypeB : SomeType 
{ 
    public SomeTypeB(string s) : base(s) { } 
} 

public class SomeTypeC : SomeType 
{ 
    public SomeTypeC(string s) : base(s) { } 
} 

注意ComputeMatchConditions是怎樣的一個黑客,因爲它依賴於ninject內部。如果這些(的WhenInjectedInto執行)改變,那麼這可能停下來工作。當然,你可以自由提供你自己的替代實現。您也可以複製WhenInjectedInto的代碼,請參閱:BindingConfigurationBuilder.cs method WhenInjectedInto(Type parent)

相關問題