[英]Auto-wiring property injection
我正在嘗試在插件樣式系統中為StructureMap使用屬性注入。
ObjectFactory.Initialize(o => o.Scan(s =>
{
s.AssembliesFromPath("path_to_assemblies");
s.WithDefaultConventions();
});
這是一個示例實現(故意簡化了T和TU的定義,因為它們只是簡單的類)
public interface IBarService
{
void Baz();
}
public class BarService : IBarService
{
public void Baz() { /* implementation */ }
}
public abstract class PluginBase<T, TU> : IPlugin
where T : AClass, new()
where TU : BClass
{
protected PluginBase()
{
//some init code in the constructor
}
}
//Foo is created at run-time via Activator.CreateInstance()
public class FooPlugin : PluginBase<AClass, BClass>
{
[SetterProperty]
public IBarService BarService { get; set; }
public void Fooey()
{
BarService.Baz();
}
}
我想自動關聯在運行時創建的所有這些插件的屬性依賴關系。 我以為我將從屬性注入開始,然后在需要時將其移至構造函數。
如果我做:
var obj = ObjectFactory.GetInstance<IBarService>();
在FooPlugin
實例中的任何地方,我都能獲得正確的實現,一切都很好。
如果我做:
this.BarService.Baz();
我得到一個空引用異常,因為未設置IBarService
實例。
創建插件后,如果執行以下操作:
ObjectFactory.BuildUp(pluginObject)
。
一切都很好, FooPlugin
具有的正確實施IBarService
。
有什么方法可以讓我簡單地用[SetterProperty]
裝飾我的插件屬性,並在創建插件時讓StructureMap自動注入那些插件屬性,而不必調用ObjectFactory.BuildUp(pluginObject)
?
在無效的情況下,如何創建插件實例? 您只是在做new FooPlugin()
嗎?
如果您執行var plugin = ObjectFactory.GetInstance<PluginBase<AClass, BClass>>();
,您是否已解決所有正確的依賴關系的插件?
如果使用“ new”實例化對象,則容器將無法知道實例需要解決依賴關系-它不知道該實例。 可以說,需要注入依賴項的實例必須由容器“管理”。
如果您只走相反的路線,並將所有依賴項注入到構造函數中,將為您省去很多麻煩。 這樣,您可以在一個地方檢查對象是否正確初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.