In this article, we will discuss how to resolve DBConext entityFramwork Class with help of unity
container and able to inject into Repository class. It will provide the scope
to write unit testing for repository class against Mocked DBContext.
Unit Container Mapping (In Config)
<unity>
<register name ="DBEntities" type="Sample.DataAccess.DBEntities,Sample.DataAccess"/>
</container>
</unity>
If DbContext Class have any property or constructor
parameter dependency, add below configuration settings .
<register name ="DBEntities" type="Sample.DataAccess.DBEntities,Sample.DataAccess">
<constructor>
<param name="dependency
" type="Idependency">
<dependency name="Idependency"/>
</param>
</constructor>
</register>
Unit Container Mapping (In Class)
var container = new UnityContainer();
container.RegisterType<IRepository, Repository>();
container.RegisterType<IRepository, Repository>();
container.RegisterType<DbContext, DBEntities>();
Repository Interface & Class :
here are repository interface and its implemented class
here are repository interface and its implemented class
public interface IRepository
{
Employee Get(int ID);
int Create(Employee employee);
void Delete(int id);
int
Update(Employee employee);
}
public class Repository : IRepository
{
private DBEntities _db;
public Repository(DBEntities db)
{
_db = db;
}
}
in repositoty class, DBEntities class is being resolved by unity .
public partial class DBEntities : DbContext
in repositoty class, DBEntities class is being resolved by unity .
public partial class DBEntities : DbContext
{
public DBEntities()
: base("name=DBEntities")
{
}
}
other posts related to dependency injection and unity container
Thanks for Visiting !!
No comments:
Post a Comment