2013-03-16 75 views
0

我有一個綁定到某一類接口。一切工作都像例外。我想用構造函數注入創建類,而無需將內核傳遞到任何地方。我想爲這些建議設立一個單身工廠。我如何創建一個不使用ninject.extensions.factory庫。Ninject辛格爾頓廠

+0

請提供您的應用程序類型(EXE/WF /服務/ MVC) - 也有一些相關的每個技術utils的? – 2013-03-16 18:40:20

+0

它的WPF,但我需要它在一個數據模型類裏面沒有任何viewmodel什麼的。 – 2013-03-16 18:41:37

回答

2

如果你想創建一個工廠,但沒有使用的工廠擴展(不知道爲什麼,這是你需要的東西在這裏我想)你可以做類似如下:

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只是在運行時爲您完成所有工作。你只需要定義工廠接口,擴展就可以動態地創建實現。

0

試試這個代碼:

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>(); 
    } 
} 
+2

我不建議走這條路,因爲它是服務定位器反模式的一個例子:http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/ – rossipedia 2013-03-16 18:46:19

+0

它是一個可以接受的設計模式做它喜歡這些? – 2013-03-16 18:46:38

+0

檢查代碼.. – 2013-03-16 18:55:36