Home > Net >  Questions about the Autofac generic injection
Questions about the Autofac generic injection

Time:09-22

If I have the interface and implementation:
 
Public interface IRepository : IRepository where TEntity: class, IEntity

Public class EfRepository : IRepository
Where TDbContext: IEfDbContext
Where TEntity: class, IEntity


Using Autofac as IOC container:
 
Builder. RegisterGeneric (typeof (EfRepository<, & gt;) ). The As (typeof (IRepository<& gt;) );


Write complains, should how to write, strives for the great god,

CodePudding user response:

AutoFac generic injection, need enough information, such as
IMyInterface Can be mapped to MyImplementation; That is to say IMyInterface<> Can be mapped to MyImplementation<> ,
IUnit; That is to say IUnit<, & gt; Can be mapped to UnitImplementation<, & gt; ,

As you can see, IRepository<> Cannot be automatically mapped to EfRepository<, & gt; ,
Because IRepository<> Only provide a generic types, and create EfRepository<, & gt; Need to know two generic types,


Depends on your logic, if EfRepository instance do need two generic types, request service also need two generic type information, may be able to write like this:
Public class EfRepository : IRepository TDbContext & gt;
Where TDbContext: IEfDbContext
Where TEntity: class, IEntity
{/*... */}

At this point, the generic injection is:
Builder. RegisterGeneric (typeof (EfRepository <, & gt; ). The As (typeof (IRepository <, & gt; ));



  •  Tags:  
  • C#
  • Related