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



我正在尝试绑定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>>();(或者,当然,更好的是,将其注入到构造函数中)。

相关内容

最新更新