激活IEntityRepository时出错{SomeEntity}有多个匹配的绑定可用。匹配绑定

时间:2014-10-01 15:16:19

标签: asp.net-web-api dependency-injection ninject

队 我遇到了以下错误。

激活IEntityRepository {SomeEntity}时出错

可以使用多个匹配的绑定。

匹配绑定:

1)从IEntityRepository {T}绑定到EntityRepository {T}   2)从IEntityRepository {T}绑定到EntityRepository {T}

激活路径:

2)将依赖IEntityRepository {SomeEntity}注入到AccountController类型构造函数的someRepository参数中   1)对AccountController的请求

建议:   1)确保您只为IEntityRepository {SomeEntity}定义了一次绑定。

我的NInjectDependencyResolver如下。

 public class NInjectDependencyResolver : NInjectScope, {
    private readonly IKernel m_Kernel;
    public NInjectDependencyResolver(IKernel kernel) : base(kernel)
    {
        m_Kernel = kernel;

        // Configure by convention
        m_Kernel.Bind(x => x.FromAssembliesMatching("Id2.*.dll").SelectAllClasses().BindAllInterfaces());

     // I tried even the following explicit binding. But exactly same error. // m_Kernel.Bind(typeof(IEntityRepository<>)).To(typeof(EntityRepository<>)).InSingletonScope();

    }

    public IDependencyScope BeginScope()
    {
        return new NInjectDependencyResolver(m_Kernel);
    }
}


public class NInjectScope : IDependencyScope
{
    protected IResolutionRoot m_ResolutionRoot;
    internal NInjectScope(IResolutionRoot kernel)
    {
        m_ResolutionRoot = kernel;
    }
    public object GetService(Type serviceType)
    {
        IRequest request = m_ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return m_ResolutionRoot.Resolve(request).SingleOrDefault();
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        IRequest request = m_ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return m_ResolutionRoot.Resolve(request).ToList();
    }
    public void Dispose()
    {
        IDisposable disposable = (IDisposable)m_ResolutionRoot;
        if (disposable != null)
            disposable.Dispose();
        m_ResolutionRoot = null;
    }
}

1 个答案:

答案 0 :(得分:0)

在公共IDependencyScope BeginScope {}方法中,而不是

返回新的NInjectDependencyResolver(m_Kernel);

如果我使用

返回新 NInjectScope(m_Kernel.BeginBlock());

完美的工作。

here获得。