This article will demonstrate how to get the data using Dapper and Repository Pattern in Web API and how to use Dependency Injection using the Unit of Work in Web API. I will show you how to implement the Generic Repository with Custom Repository for CRUD operations.

What is Dapper?
What is Web API?
What is Repository Pattern?
Web API Project with Data Access Layer
- Entities- This will contain all the entity class files.
- Infrastructure- It will include all data access required files, like connection class.
- Repositories- This will include Generic and Custom Repositories.
- Services- It includes all the business logic related classes.
- UnitOfWork- This is an important folder for this demonstration which includes UnitOfWork Class for transaction.
- Test API:-It is a Web API project for creating HTTP enabled services.
Our project structure will be like the following image.
Inside the Infrastructure folder, create an interface named as IConnectionFactory which contains the GetConnection property that returns IDbConnection type connection. Implement IConnectionFactory interface with ConnectionFactory class. IDbConnection handles all the database connection related queries.

- public class ConnectionFactory : IConnectionFactory
- {
- private readonly string connectionString = ConfigurationManager.ConnectionStrings["DTAppCon"].ConnectionString;
- public IDbConnection GetConnection
- {
- get
- {
- var factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
- var conn = factory.CreateConnection();
- conn.ConnectionString = connectionString;
- conn.Open();
- return conn;
- }
- }
- }
- public class Blog
- {
- public int PostId { get; set; }
- public string PostTitle { get; set; }
- public string ShortPostContent { get; set; }
- public string FullPostContent { get; set; }
- public string MetaKeywords { get; set; }
- public string MetaDescription { get; set; }
- public DateTime PostAddedDate { get; set; }
- public DateTime PostUpdatedDate { get; set; }
- public bool IsCommented { get; set; }
- public bool IsShared { get; set; }
- public bool IsPrivate { get; set; }
- public int NumberOfViews { get; set; }
- public string PostUrl { get; set; }
- public virtual int CategoryId { get; set; }
- public virtual Category Categories { get; set; }
- }
- public interface IGenericRepository<TEntity> where TEntity : class
- {
- TEntity Get(int Id);
- IEnumerable<TEntity> GetAll();
- void Add(TEntity entity);
- void Delete(TEntity entity);
- void Update(TEntity entity);
- }
- public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
- {
- public void Add(TEntity entity)
- {
- throw new NotImplementedException();
- }
- public void Delete(TEntity entity)
- {
- throw new NotImplementedException();
- }
- public void Update(TEntity entity)
- {
- throw new NotImplementedException();
- }
- public TEntity Get(int Id)
- {
- throw new NotImplementedException();
- }
- public IEnumerable<TEntity> GetAll()
- {
- throw new NotImplementedException();
- }
- }
Implementation Dapper with Data Access Project
For adding Dapper with your project, just open Package Manager Console from the Tools menu and install Dapper using this command
Install-Package Dapper
It will also add and resolve the dependent dependencies for Dapper. At last, it will show success message for installation of Dapper.

Custom Repository and Implementation
- public class BlogRepository : GenericRepository<Blog>, IBlogRepository
- {
- IConnectionFactory _connectionFactory;
- public BlogRepository(IConnectionFactory connectionFactory)
- {
- _connectionFactory = connectionFactory;
- }
- public async Task<IEnumerable<Blog>> GetAllBlogByPageIndex(int pageIndex, int pageSize)
- {
- var query = "usp_GetAllBlogPostByPageIndex";
- var param = new DynamicParameters();
- param.Add("@PageIndex", pageIndex);
- param.Add("@PageSize", pageSize);
- var list = await SqlMapper.QueryAsync<Blog>(_connectionFactory.GetConnection, query, param, commandType: CommandType.StoredProcedure);
- return list;
- }
- }
- public class UnitOfWork : IUnitOfWork
- {
- private readonly IBlogRepository _blogRepository;
- public UnitOfWork(IBlogRepository blogRepository)
- {
- _blogRepository = blogRepository;
- }
- void IUnitOfWork.Complete()
- {
- throw new NotImplementedException();
- }
- public IBlogRepository BlogRepository
- {
- get
- {
- return _blogRepository;
- }
- }
- }
- public class BlogService : IBlogService
- {
- IUnitOfWork _unitOfWork;
- public BlogService(IUnitOfWork unitOfWork)
- {
- _unitOfWork = unitOfWork;
- }
- public async Task<IEnumerable<Blog>> GetAllBlogByPageIndex(int pageIndex, int pageSize)
- {
- return await _unitOfWork.BlogRepository.GetAllBlogByPageIndex(pageIndex, pageSize);
- }
- }
Implement UnityResolver with Web API

- public class UnityResolver : IDependencyResolver
- {
- protected IUnityContainer container;
- public UnityResolver(IUnityContainer container)
- {
- if (container == null)
- {
- throw new ArgumentNullException("container");
- }
- this.container = container;
- }
- public object GetService(Type serviceType)
- {
- try
- {
- return container.Resolve(serviceType);
- }
- catch (ResolutionFailedException)
- {
- return null;
- }
- }
- public IEnumerable<object> GetServices(Type serviceType)
- {
- try
- {
- return container.ResolveAll(serviceType);
- }
- catch (ResolutionFailedException)
- {
- return new List<object>();
- }
- }
- public IDependencyScope BeginScope()
- {
- var child = container.CreateChildContainer();
- return new UnityResolver(child);
- }
- public void Dispose()
- {
- container.Dispose();
- }
- }
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
- var container = new UnityContainer();
- container.RegisterType<IBlogRepository, BlogRepository>();
- container.RegisterType<IConnectionFactory, ConnectionFactory>();
- container.RegisterType<IUnitOfWork, UnitOfWork>();
- container.RegisterType<IBlogService, BlogService>();
- config.DependencyResolver = new UnityResolver(container);
- // Web API configuration and services
- // Configure Web API to use only bearer token authentication.
- config.SuppressDefaultHostAuthentication();
- config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
- // Web API routes
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
- }
- public class BlogController : ApiController
- {
- IBlogService _blogService;
- public BlogController()
- {
- }
- public BlogController(IBlogService blogService)
- {
- _blogService = blogService;
- }
- public async Task<IHttpActionResult> GetAllBlogPostsByPageIndex()
- {
- var resultData = await _blogService.GetAllBlogByPageIndex(3, 4);
- if (resultData == null)
- {
- return NotFound();
- }
- return Ok(resultData);
- }
- }
- CREATE TABLE [dbo].[NextPosts](
- [PostId] [int] NOT NULL,
- [PostTitle] [nvarchar](500) NULL,
- [ShortPostContent] [ntext] NULL,
- [FullPostContent] [ntext] NULL,
- [MetaKeywords] [nvarchar](255) NULL,
- [MetaDescription] [nvarchar](500) NULL,
- [PostAddedDate] [smalldatetime] NOT NULL,
- [PostUpdatedDate] [smalldatetime] NOT NULL,
- [IsCommented] [bit] NOT NULL,
- [IsShared] [bit] NOT NULL,
- [IsPrivate] [bit] NOT NULL,
- [NumberOfViews] [int] NOT NULL,
- [PostUrl] [nvarchar](255) NULL,
- [CategoryId] [int] NOT NULL
- )
- CREATE PROC [dbo].[usp_GetAllBlogPostByPageIndex](@PageIndex Int, @PageSize INT)
- AS
- BEGIN
- SELECT * FROM NextPosts ORDER BY PostId OFFSET((@PageIndex-1)*@PageSize) ROWS
- FETCH NEXT @PageSize ROWS ONLY;
- END
- GO
- <connectionStrings>
- <add name="DTAppCon" connectionString="server=My-computer;database=Test;UId=mukesh; Password=mukesh" providerName="System.Data.SqlClient" />
- </connectionStrings>


Keyur SuraniPosted Dec 16, 2021, 2:41 PM
Sir download URL is not working, please provide that
Sujoy AdhikaryPosted Sep 29, 2021, 6:29 AM
Where is SqlMapper declared???????????????????
Monika PrajapatiPosted Jun 29, 2021, 9:45 PM
Any one has the source code for this , please share
Rodrigo Alarcón SantiniPosted Apr 26, 2021, 12:10 AM
Source not avaliable any more..!! any chance for GitHub upload?
Guest UserPosted Jan 7, 2021, 1:37 PM
Hello, the source code link no longer works
suri surendraPosted Aug 19, 2020, 4:59 AM
Hi Mukesh, You have not implemented anything GenericRepository method's, Why?
Bhushan GuptaPosted Sep 30, 2019, 12:26 AM
Very good post
Santhosh Kumar ChandranPosted Aug 13, 2019, 1:59 AM
This is not executable, can you post the updated one? I'm getting object ref exception for Getblogs
kaushal dhoraPosted May 28, 2018, 6:44 AM
Could you please guide me if I do have multiple database then this pattern is advisable or not?
PANDI SELVARAJPosted Aug 25, 2017, 10:37 AM
Hi used the code and added another repository for another dataservice and register it. Now i am getting nullException error as it is going to default constructor instead of parameter one. How to resolve it. ? Any idea
Ajith MohanPosted Jun 14, 2017, 10:47 AM
Can you show how generic repository is implemented. Your code shows not implemented
Alexis MATHIEUPosted Mar 22, 2017, 9:03 AM
Hi ! Thanks for sharing. Can you please explain how the SQL will execute in a transaction, as the UnitOfWork.Complete method is not implemented and as the repository do not use IDbTransaction ? Thank you
Jaco ZwartsPosted Dec 11, 2016, 8:37 AM
Mukesh, thank you for sharing. Good read!
Humayun Kabir MamunPosted Sep 18, 2016, 12:24 AM
Nice...
Vignesh ManiPosted Sep 15, 2016, 4:03 PM
Nice one
Ravi PatelPosted Sep 15, 2016, 1:24 AM
Nice explanation thanks