解决通用服务
我得到了以下服务:
IRepository<TEntity, TPrimaryKey>
..为此我创建了一个实现,定义为:
Repository<TEntity, TPrimaryKey>.
如何在 autofac 中注册它,以便我可以将其解析为:
IRepository<User, int>
I got the following service:
IRepository<TEntity, TPrimaryKey>
..for which I've created an implementation defined as:
Repository<TEntity, TPrimaryKey>.
How do I register it in autofac so that I can resolve it as:
IRepository<User, int>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我喜欢autofac。
I love autofac.
作为您自己的解决方案的替代方案,您可以尝试定义一个工厂来创建新的存储库实例:
您可以按如下方式注册
RepositoryFactory
:现在您可以将
IRepositoryFactory
声明为构造函数参数并创建新实例。例如,看看这个 ProcessUserAccountUpgradeCommand 类,它使用依赖项注入来获取其依赖项:虽然使用工厂而不是直接获取存储库可能看起来有点麻烦,但您的设计将清楚地传达一个新实例是已检索(因为您调用了 CreateRepository 方法)。从 IoC 容器返回的实例通常预期寿命较长 。
另一个提示:您可能希望重构主键类型的使用。总是要求
存储库而不是仅
存储库会很麻烦。也许您找到一种方法将主键抽象到工厂内部。我希望这有帮助。
As an alternative to your own solution, you might try defining a factory for creating new repository instances:
You can register the
RepositoryFactory
as follows:Now you can declare
IRepositoryFactory
as constructor argument and create new instances. Look for instance at thisProcessUserAccountUpgradeCommand
class that uses dependency injection for its dependencies:While this might seem a bit cumbersome to use a factory instead of getting a repository directly, your design will communicate clearly that a new instance is retrieved (because you call the
CreateRepository
method). Instances returned from a IoC container are normally expected to have a long life.Another tip: You might want to refactor the use of the primary key type away. It would be cumbersome to always ask for repositories of
<User, int>
instead of just<User>
repositories. Perhaps you find a way to abstract the primary key away inside the factory.I hope this helps.