使用 Ninject 2.2 绑定通用存储库和特定存储库
我有一个在 Repository 中实现的 IRepository,并且我将特定类型的 Repository 扩展为 UsersRepository 我需要使用 Ninject 的通用绑定来绑定所有类型,但是当请求 IRepository 实例时,我需要获取 UsersRepository 而不是 Repository。
Bind<IDbContext>().To<SMSDataContext>()
.WithConstructorArgument("connectionStringName", "dbcsname");
在这里,我绑定通用存储库:
Bind(typeof(IRepository<>)).To(typeof(Repository<>))
.WithConstructorArgument("dbContext",new SMSDataContext("dbcsname"));
这里我尝试绑定特定实例:
Bind<IRepository<Setting>>().ToConstant(settingsRepository);
尝试使用“.ToConstant”和仅使用“.To”的不同方法也尝试绑定到具体实现,如下所示:
UsersRepository usersRepository = new UsersRepository(new SMSDataContext("SMSDB"));
Bind<IRepository<Setting>>().To<SettingsRepository>().WithConstructorArgument("dbContext", new SMSDataContext("dbscname")); ;
请告知。
I have a IRepository that I have implemented in Repository and I extended Repository for specific type as UsersRepository I need to bind all types using the generic binding for Ninject however when requesting instance for IRepository I need to get UsersRepository instead of Repository.
Bind<IDbContext>().To<SMSDataContext>()
.WithConstructorArgument("connectionStringName", "dbcsname");
Here I am binding the generic repository:
Bind(typeof(IRepository<>)).To(typeof(Repository<>))
.WithConstructorArgument("dbContext",new SMSDataContext("dbcsname"));
Here I am trying to bind a specific instance:
Bind<IRepository<Setting>>().ToConstant(settingsRepository);
Tried different approaches with ".ToConstant" and with only ".To" also tried to bind to concrete implementation like follows:
UsersRepository usersRepository = new UsersRepository(new SMSDataContext("SMSDB"));
Bind<IRepository<Setting>>().To<SettingsRepository>().WithConstructorArgument("dbContext", new SMSDataContext("dbscname")); ;
Please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
目前只能使用一些作弊,因为开放式通用绑定与封闭式通用绑定具有相同的优先级。但是您可以通过添加条件来提高绑定的优先级。
Currently it is only possible using some cheat because open generic bindings have the same priority as closed generic bindings. But you can increase the priority of a binding by adding a condition.