我有一個綁定到某一類接口。一切工作都像例外。我想用構造函數注入創建類,而無需將內核傳遞到任何地方。我想爲這些建議設立一個單身工廠。我如何創建一個不使用ninject.extensions.factory庫。Ninject辛格爾頓廠
回答
如果你想創建一個工廠,但沒有使用的工廠擴展(不知道爲什麼,這是你需要的東西在這裏我想)你可以做類似如下:
public class FooFactory : IFooFactory
{
// allows us to Get things from the kernel, but not add new bindings etc.
private readonly IResolutionRoot resolutionRoot;
public FooFactory(IResolutionRoot resolutionRoot)
{
this.resolutionRoot = resolutionRoot;
}
public IFoo CreateFoo()
{
return this.resolutionRoot.Get<IFoo>();
}
// or if you want to specify a value at runtime...
public IFoo CreateFoo(string myArg)
{
return this.resolutionRoot.Get<IFoo>(new ConstructorArgument("myArg", myArg));
}
}
public class Foo : IFoo { ... }
public class NeedsFooAtRuntime
{
public NeedsFooAtRuntime(IFooFactory factory)
{
this.foo = factory.CreateFoo("test");
}
}
Bind<IFooFactory>().To<FooFactory>();
Bind<IFoo>().To<Foo>();
Factory Extension只是在運行時爲您完成所有工作。你只需要定義工廠接口,擴展就可以動態地創建實現。
試試這個代碼:
class NinjectKernelSingleton
{
private static YourKernel _kernel;
public static YourKernel Kernel
{
get { return _kernel ?? (_kernel = new YourKernel()); }
}
}
public class YourKernel
{
private IKernel _kernel;
public YourKernel()
{
_kernel = InitKernel();
}
private IKernel InitKernel()
{
//Ninject init logic goes here
}
public T Resolve<T>()
{
return _kernel.Get<T>();
}
}
我不建議走這條路,因爲它是服務定位器反模式的一個例子:http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/ – rossipedia 2013-03-16 18:46:19
它是一個可以接受的設計模式做它喜歡這些? – 2013-03-16 18:46:38
檢查代碼.. – 2013-03-16 18:55:36
- 1. 辛格爾頓工廠在PHP
- 2. 辛格爾頓ExtJs4
- 3. jQuery的辛格爾頓
- 4. 辛格爾頓Imlementation類
- 5. 什麼是辛格爾頓
- 6. 辛格爾頓 - 有道
- 7. Unity3D辛格爾頓用MonoBehavior
- 8. 辛格爾頓NServiceBus佐賀
- 9. 辛格爾頓溶液
- 10. PHP OOP辛格爾頓
- 11. 辛格爾頓實例
- 12. 辛格爾頓問題
- 13. 辛格爾頓與JBoss SEAM
- 14. 實現辛格爾頓使用工廠方法
- 15. 春天 - 辛格爾頓工廠實例原型作用域bean
- 16. 辛格爾頓對象和Java servlet
- 17. 傳遞對象與辛格爾頓
- 18. 辛格爾頓C++模板類
- 19. PHP類父實例(辛格爾頓)
- 20. 辛格爾頓在Java參數再次
- 21. 辛格爾頓的NSMutableDictionary和plist中
- 22. 辛格爾頓和單元測試
- 23. 使用數據管理辛格爾頓
- 24. 訪問播放辛格爾頓方法
- 25. 純靜態類VS辛格爾頓
- 26. 辛格爾頓對象處置
- 27. 春辛格爾頓線程安全
- 28. 辛格爾頓在科特林
- 29. 斯威夫特3 - 辛格爾頓
- 30. 辛格爾頓Implemenatatio鏈接錯誤
請提供您的應用程序類型(EXE/WF /服務/ MVC) - 也有一些相關的每個技術utils的? – 2013-03-16 18:40:20
它的WPF,但我需要它在一個數據模型類裏面沒有任何viewmodel什麼的。 – 2013-03-16 18:41:37