Ninject 绑定有什么问题?收到 "no implicit reference conversion" 错误

What is wrong with this Ninject binding? Getting "no implicit reference conversion" error

我正在尝试绑定 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'.

我做错了什么?

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

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>>(); (或者,当然更好,将其注入构造函数)。