C# 基于对象的Ninject绑定&x27;谁的财产?约定还是上下文约束?

C# 基于对象的Ninject绑定&x27;谁的财产?约定还是上下文约束?,c#,binding,ninject,ninject-extensions,contextual-binding,C#,Binding,Ninject,Ninject Extensions,Contextual Binding,我有一个界面: 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

我有一个界面:

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");
Bind().To.When(obj.Name==“C1”);
Bind().To.When(obj.Name==“C2”);

但我以前从未和Ninject合作过。有什么想法吗?

我对你的问题的解释有些开明,因为我认为你跳过了一些“思考步骤”和必要的信息

但是,我建议这样做:

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);
    }
}
INamed公共接口
{
字符串名称{get;}
}
公共接口工厂
{
界面创建(未命名对象);
}
公共类工厂:IFactory
{
私有只读IResolutionRoot resolutionRoot;
公共工厂(IResolutionRoot resolutionRoot)
{
this.resolutionRoot=resolutionRoot;
}
公共界面创建(INamed obj)
{
返回this.resolutionRoot.Get(obj.Name);
}
}
备选方案:您也可以使用。遗憾的是,默认情况下,它不支持命名绑定,但您可以像文档一样对其进行自定义


然而,坦率地说,我宁愿手动实现工厂,因为它更容易理解。如果我要定制工厂——我已经做了——我会考虑增加对属性的支持(它指定如何处理一个工厂方法参数),而不是必须配置每个<代码> .toFACTROYY()/<代码>绑定它将如何解释参数。

我想你弄乱了你的例子。如果需要访问
IInterface
的实例,那么如何实例化
IInterface
?你不能。你的意思是将带有
名称
属性的
obj
传递给工厂,然后工厂返回
界面
?请你“修复”这个问题,以便Q/a对以后的读者也有价值吗?谢谢,谢谢!我的一个朋友也建议采用工厂模式。你能澄清一下它的IResolutionRoot部分吗?ninject的内核正在实现
IKernel
接口,该接口反过来又派生自
IBindingRoot
IResolutionRoot
IBindingRoot
用于创建绑定(
Bind().To()…
),而
IResolutionRoot
用于检索/实例化类型。您不需要绑定
,它已经被ninject绑定了。例如,ninject工厂扩展在内部也使用
IResolutionRoot
来实例化类型。