这个Ninject绑定有什么问题?获取"没有隐式参考转换"错误

时间:2015-01-19 14:39:45

标签: c# ninject

我正在尝试绑定ICustomerRepository

public interface ICustomerRepository : IMongoRepository<Customer> { }

public interface IMongoRepository<T> : IMongoRepository { }

public interface IMongoRepository
{
    bool SaveToMongo(string contentToSave);
}

MongoRepository<Customer>

public class MongoRepository<T> : IMongoRepository<T>
{
    MongoDatabase _database;
    public MongoRepository(MongoDatabase database)
    {
        _database = database;
    }

    public virtual bool SaveToMongo(string contentToSave)
    {
        // ...
    }
}

通过这样做:

kernel.Bind<ICustomerRepository>().To<MongoRepository<Customer>>().Named("Customer").WithConstructorArgument(kernel.TryGet<MongoDatabase>());;

但我收到错误The type 'MongoRepository<Customer>' cannot be used as type parameter 'TImplementation' in the generic type or method 'Ninject.Syntax.IBindingToSyntax<T1>.To<TImplementation>()'. There is no implicit reference conversion from 'MongoRepository<Customer>' to 'ICustomerRepository'.

我做错了什么?

1 个答案:

答案 0 :(得分:3)

如果您真的想采用这种方法,那么您需要添加的是:

public class CustomerMongoRepository : MongoRepository<Customer>, ICustomerRepository
{
....
}

Bind<ICustomerRepository>().To<CustomerMongoRepository>()
.Named("Customer")
.WithConstructorArgument(kernel.TryGet<MongoDatabase>());

但是,由于您已经拥有50个实体,因此您似乎不太可能想要创建50个存储库实现,除了继承自MongoRepository<T>之外什么都不做。

那么,为什么不完全跳过ICustomerRepository界面而不是IMongoRepository<Customer>

Bind(typeof(IMongoRepository)).To(typeof(MongoRepository))
    .WithConstructorArgument(kernel.TryGet<MongoDatabase>());

然后你可以使用它:kernel.Get<IMongoRepository<Customer>>(); (或者当然,更好的是,将它注入构造函数中)。