【发布时间】:2015-06-20 12:17:23
【问题描述】:
我需要根据从数据库中获取的字符串创建共享通用接口 (IFoo) 的对象。我有“A”,我需要实例化 AFoo,我得到“B”,我需要生产 BFoo,等等。我首先想到的是一个工厂。但是创建的对象(AFoo,BFoo)需要注入它们的依赖项(并且这些依赖项需要更多的依赖项,甚至需要一些参数)。对于所有的注入,我使用 Ninject,它本身似乎是一个花哨的工厂。为了在我的工厂中创建对象,我通过构造函数注入 Ninject 的内核。这是理想的方式吗?
interface IBar { }
class Bar : IBar {
public Bar(string logFilePath) { }
}
interface IFoo { }
class AFoo : IFoo {
public AFoo(IBar bar) { }
}
class BFoo : IFoo { }
class FooFactory : IFooFactory {
private IKernel _ninjectKernel;
public FooFactory(IKernel ninjectKernel) {
_ninjectKernel = ninjectKernel;
}
IFoo GetFooByName(string name) {
switch (name) {
case "A": _ninjectKernel.Get<AFoo>();
}
throw new NotSupportedException("Blabla");
}
}
class FooManager : IFooManager {
private IFooFactory _fooFactory;
public FooManager(IFooFactory fooFactory) {
_fooFactory = fooFactory;
}
void DoNastyFooThings(string text) {
IFoo foo = _fooFactory.GetFooByName(text);
/* use foo... */
}
}
class Program {
public static void Main() {
IKernel kernel = new StandardKernel();
kernel.Bind<IBar>.To<Bar>();
kernel.Bind<IFooManager>.To<FooManager>();
kernel.Bind<IFooFactory>.To<FooFactory>();
IFooManager manager = kernel.Get<IFooManager>(new ConstructorArgument("ninjectKernel", kernel, true));
manager.DoNastyFooThings("A");
}
}
【问题讨论】:
标签: c# dependency-injection ninject