クラスにバインドされたインターフェイスがあります。すべてが例外のように機能します。カーネルをどこにでも渡さずに、コンストラクター インジェクションを使用してクラスを作成したいと考えています。これらの提案のためのシングルトンファクトリーが欲しいです。ninject.extensions.factory ライブラリを使用せずに作成するにはどうすればよいですか。
2 に答える
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 拡張機能は、実行時にそのすべての作業を行うだけです。ファクトリ インターフェイスを定義するだけでよく、拡張機能によって実装が動的に作成されます。
于 2013-03-16T20:12:09.253 に答える
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>();
}
}
于 2013-03-16T18:44:04.697 に答える