我需要一个工厂类在它返回一个实例之前做一些工作,所以我有一个这样的工厂方法:
public Foo Create(string bar, IEnumerable<SomeMetaData> metaData)
{
var meta = new ObservableCollection<AnotherType>(
metaData.Select(e => new AnotherType { ... }).ToList());
return Create(new ConstructorArgument("bar", bar),
new ConstructorArgument("metaData", meta));
}
具体工厂类派生自一个基础工厂,它省去了我的实际布线,以防你想知道它们IResolutionRoot
去了哪里:
public abstract class FactoryBase<T> where T : class
{
private IResolutionRoot _resolutionRoot;
protected FactoryBase(IResolutionRoot resolutionRoot)
{
_resolutionRoot = resolutionRoot;
}
protected T Create(params IParameter[] parameters)
{
return _resolutionRoot.Get<T>(parameters);
}
}
(如果有人想对此发表评论,我对 CodeReview 有疑问:https ://codereview.stackexchange.com/questions/25038/are-there-side-effects-to-having-a-generic-ninject -工厂)
问题是在 NinjectModule 中,我不知道如何告诉 Ninject 使用该特定的具体FooFactory
类:
Bind<IFooFactory>().ToFactory(); // uses an abstract factory that doesn't do what I need
Bind<IFooFactory>().ToFactory<FooFactory>(); // doesn't build
我相信我需要的是这样的:
Bind<IFooFactory>().ToFactory<FooFactory>(Func<FooFactoryInstanceProvider>);
我需要做什么才能提供这个InstanceProvider
?可能这只是我的误解,Func<T>
但我发现http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/对此过于模糊。
我想出了这个:
public class FooFactoryInstanceProvider : StandardInstanceProvider
{
protected override Type GetType(MethodInfo methodInfo, object[] arguments)
{
return typeof(FooFactory);
}
}
到目前为止,一切都很好?下一步是什么?