我有一个界面:
public interface IInterface
{
string Get(obj o);
}
我有两个班级:
public class C1 : IInterface
{
string Get(obj o);
}
public class C2 : IInterface
{
string Get(obj o);
}
我想发送o然后让Ninject根据o的属性确定它是哪个接口。 Obj就像:
public class obj
{
public string Name {get;set;}
public int Id {get;set;}
}
我喜欢这样的东西:
Bind<IInterface>().To<C1>.When(obj.Name == "C1");
Bind<IInterface>().To<C2>.When(obj.Name == "C2");
但我以前没有和Ninject合作过。有什么想法吗?
答案 0 :(得分:1)
我对你的问题的解释有些自由,因为我认为你已经跳过了一些“思考步骤”和必要的信息。
但是,我建议这样做:
public interface INamed
{
string Name { get; }
}
public interface IFactory
{
IInterface Create(INamed obj);
}
public class Factory : IFactory
{
private readonly IResolutionRoot resolutionRoot;
public Factory(IResolutionRoot resolutionRoot)
{
this.resolutionRoot = resolutionRoot;
}
public IInterface Create(INamed obj)
{
return this.resolutionRoot.Get<IInterface>(obj.Name);
}
}
替代:您也可以使用ninject factory extension。遗憾的是,默认情况下它不支持命名绑定,但您可以像记录here一样自定义它。
然而,坦率地说,我宁愿去手动实施工厂,因为它更容易理解。如果我要自定义工厂 - 我已经完成了 - 我会考虑添加对属性的支持(指定如何处理工厂方法参数),而不是必须配置每个.ToFactory()
绑定它将如何解释参数。 / p>