假如我有介面及實作:
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<>));
這樣寫會報錯,應該如何寫呢,求大神指點。
uj5u.com熱心網友回復:
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<,>));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/71673.html
標籤:C#
