2011-11-28 100 views
6

我以前從未使用過Windsor,但使用過其他DI框架,此刻我遇到了一個相當奇怪的問題。Castle Windsor 3以構造函數參數作爲字符串

我有一個工廠類,它需要一個字符串在其構造,但是每當我試圖解決該對象我得到一個異常說:

Handler for System.String was not found. 

<Message>Handler for System.String was not found.</Message> 
<StackTrace>at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.TryGetHandlerFromKernel(DependencyModel dependency, CreationContext context) in d:\60b7fa65294e7792\src\Castle.Windsor\MicroKernel\Resolvers\DefaultDependencyResolver.cs:line 403 
at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveCore(CreationContext context, ComponentModel model, DependencyModel dependency) in d:\60b7fa65294e7792\src\Castle.Windsor\MicroKernel\Resolvers\DefaultDependencyResolver.cs:line 270</StackTrace> 
<Type>Castle.MicroKernel.Handlers.HandlerException</Type> 
</InnerException> 
<Message>Missing dependency. 
Component SomeExampleFactory has a dependency on System.String, which could not be resolved. 
Make sure the dependency is correctly registered in the container as a service, or provided as inline argument.</Message> 

類看起來類似:

public interface IDummyFactory 
{ 
    void DoSomething(); 
} 

public class DummyFactory : IDummyFactory 
{ 
    private string someString; 

    public DummyFactory(string someConstructorArg) 
    { 
     someString = someConstructorArg; 
    } 
} 

使用DI設置如下:

var someString = "some constructor arg"; 
_container.Register(Component.For<IDummyFactory>().ImplementedBy<DummyFactory>().DependsOn(someString)); 

我假設它試圖做一些類型的鑄造或格式化導致它被炸出來,但由於類型本身是一個字符串,並且該變量被傳遞給一個字符串......它甚至可能是一種情況,它試圖映射該變量的類型而不是變量的內容,但我不知道有足夠的瞭解這附近的DI框架和文檔

+0

哪個版本的溫莎城堡? –

回答

8

嘗試調用的DependsOn超載這需要鍵/值對的IDictionary指定依賴:

_container.Register(
    Component.For<IDummyFactory>() 
     .ImplementedBy<DummyFactory>() 
     .DependsOn(new Hashtable 
     { 
      { "someConstructorArg", "some constructor arg" } 
     })); 
10

我也在尋找這個答案,看起來他們現在有一些簡單的東西,他們稱之爲「內聯依賴」,這是通過(其他方式)D依賴.OnValue()方法。

下面是從文檔的一般示例:

var twitterApiKey = @"the key goes here"; 

container.Register(
    Component.For<ITwitterCaller>().ImplementedBy<MyTwitterCaller>() 
     .DependsOn(Dependency.OnValue("APIKey", twitterApiKey)) 
    ); 

它將使用值twitterApiKey爲的名稱爲「APIKey」(不區分大小寫)的參數中。

http://docs.castleproject.org/Windsor.Inline-Dependencies.ashx

它看起來像這樣可能已經在3.1版本以上的,但我不能完全破譯它們的更新標記約定。

相關問題