2013-01-22 26 views
2

我正在注入我的依賴到我的類罰款,但我想知道是否有可能得到我注入類名稱?有無論如何獲取實例注入的類名稱(使用ninject)?

例如:

Bind<ISomething>.ToMethod(c => new Something([GIVE INJECTING *TO* CLASS NAME])); 

所以,如果我有:

public class Blah{ 
    public Blah(ISomething something) { /**/ } 
} 

在注入Ninject將有效呼叫:

new Blah(new Something("Blah")); 

可以這樣做?

回答

3

是的,它可以做到。使用IContext你在ToMethod方法給獲得你被注入到像這樣類型的名稱:

Bind<ISomething>().ToMethod(c => new Something(GetParentTypeName(c))); 

使用這種小幫手方法(也可以變成一個很好的擴展方法):

private string GetParentTypeName(IContext context) 
{ 
    return context.Request.ParentRequest.ParentRequest.Target.Member.DeclaringType.Name; 
} 
0

它可能已在更高版本的Ninject中進行了更改。至於版本v3.2.0,接受的解決方案並不適合我。

下做雖然:

Bind<ISomething>().ToMethod((ctx) 
     => new Something(ctx.Request.Target?.Member?.DeclaringType?.Name ?? "")); 
相關問題