我正在尝试绑定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'.
我做错了什么?
答案 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>>();
(或者当然,更好的是,将它注入构造函数中)。