我有第三方庫返回類實例。這是我的cotrol,但我想用Unity
在其公共財產inyect。由於我不能將DependecyAttribute
添加到其屬性中,因爲該類不是部分的,也不是inheritalbe,所以我想知道是否可以使用Unity
XML配置來執行檢查。沒有依賴屬性的Unity BuildUp
是否可以使用Unity's
XML配置來配置構建依賴關係?如果答案是肯定的。如何配置XML來做到這一點?
我已經試過:如果Unity Resolve
ThidPartyObj
買不BuilUp
(服務屬性空引用)工作
<register type="IService" mapTo="Service"> <!--Service has public constructor-->
</register>
<!--ThirdPartyObj has no interface and no public constructor-->
<register type="ThirdPartyObj " mapTo="ThirdPartyObj">
<!-- Inject the property "Service" -->
<property name="Service" /> //type of the property is IService
</register>
這個配置將工作,不能Resolve
ThirdPartyObj
因爲沒有公開的構造函數。
什麼,我想archieve簡單的例子:
IUnityContainer uc = New UnityContainer() //create container
container.LoadConfiguration() // load from XML config
ThirdPartyObj foo = ThirdPartyLibrary.getFooInstace() //get third party instance
container.BuildUp(foo.getType, foo) //inyect dependencies
Console.WriteLine(foo.Service.getServiceMessage)
謝謝Tuzo!至少我有確認我正確的方式。必須是沒有很好地confjured因爲我想你的例子和foo.Service在我的調試器中爲空。這很奇怪。在接受你的答案之前,給我一些時間在我的配置中查找錯誤。 – jlvaquero
我剛剛創建了一個新項目,複製粘貼我的代碼,我的配置和一直運行良好。 – jlvaquero