NInject一个带覆盖的默认绑定

时间:2014-08-12 06:54:10

标签: c# .net ninject

我的代码是......

public interface IEntityA : IGenericEntity { ... }
public interface IEntityB : IGenericEntity { ... }
....
public interface IEntityZ : IGenericEntity { ... }

public class EntityComparer<T> : IEqualityComparer<T> where T : IGenericEntity
{
...
}

public class ZComparer : EntityComparer<IEntityZ>
{
... some overrides
} 

...绑定

Bind(typeof(IEqualityComparer<>)).To(typeof(EntityComparer<>));
Bind<IEqualityComparer<IEntityZ>>().To<ZComparer>();

这个有效!那么当你再问这样的情况时......

var aComparer = Kernel.Get<IEqualityComparer<IEntityA>>(); 
// gives you an instance of EntityComparer<IEntityA>>
var bComparer = Kernel.Get<IEqualityComparer<IEntityB>>(); 
// gives you an instance of EntityComparer<IEntityB>>
var zComparer = Kernel.Get<IEqualityComparer<IEntityZ>>(); 
// gives you an instance of ZComparer

但是我想确保这些绑定仅影响实体。如果我将绑定更改为...

Bind(typeof(IEqualityComparer<>)).To(typeof(EntityComparer<>))
 .When(r => typeof(IGenericEntity).IsAssignableFrom(r.Service.GetGenericArguments()[0]));
Bind<IEqualityComparer<IEntityZ>>().To<ZComparer>();

特定实体的绑定存在问题......

var zComparer = Kernel.Get<IEqualityComparer<IEntityZ>>(); 
// gives you an instance of EntityComparer<IEntityZ>>  - undesired !

最好的方法是什么?

0 个答案:

没有答案