关于Autofac泛型注入的问题

dream__life 2020-02-07 05:24:47
假如我有接口及实现:

public interface IRepository<TEntity> : IRepository where TEntity : class, IEntity

public class EfRepository<TDbContext, TEntity> : IRepository<TEntity>
where TDbContext : IEfDbContext
where TEntity : class, IEntity


使用Autofac作为IOC容器:

builder.RegisterGeneric(typeof(EfRepository<,>)).As(typeof(IRepository<>));


这样写会报错,应该如何写呢,求大神指点。
...全文
230 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
github_36000833 2020-02-08
  • 打赏
  • 举报
回复
AutoFac泛型注入,需要足够信息,比如 IMyInterface<T>可以映射到MyImplementation<T>;也就是说IMyInterface<>可以映射到MyImplementation<>。 IUnit<T1, T2>可以映射到UnitImplementation<R,S>;也就是说IUnit<,>可以映射到UnitImplementation<,>。 可以看到,IRepository<>不能自动映射到EfRepository<,>, 因为IRepository<>只能提供一个泛型类型,而创建EfRepository<,>需要知道两个泛型类型。 取决于你的逻辑,如果EfRepository实例的确需要两个泛型类型,请求服务时也需要两个泛型类型信息。或许可以这样写: public class EfRepository<TDbContext, TEntity> : IRepository<TEntity, TDbContext> where TDbContext : IEfDbContext where TEntity : class, IEntity {/*...*/} 这时,泛型注入就是: builder.RegisterGeneric(typeof(EfRepository<,>)).As(typeof(IRepository<,>));

111,125

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧