Friday, August 11, 2017

Dependency Injection with Entity Framework DbContext

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<IRepositoryRepository>();
container.RegisterType<DbContext, DBEntities>();

Repository Interface & 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
    {
        public DBEntities()
            : base("name=DBEntities")
        {
        }

    }

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...