mercredi 22 mars 2017

Repository Design Pattern with Dapper

This is maybe more a question for code review rather than stack overflow.

I am using Dapper for a MicroORM to retrieve and Save Data to SQL Server 2014. I have got DTO classes in a DTO Proj that represent the Data retrieved from the DB or saved to the DB.

I am using the Repository Pattern so at my Service layer if a repository is required I am using constructor DI to inject that dependency and then call the method on the Repository to do the work.

so let say I have 2 services called CustomerService and CarService.

I then have 2 Repositories a CustomerRepository and a CarRepository.

I have an interface which defines all the methods in each Repository and then the concrete implementations.

An example method is shown below (calling a Stored Proc to do the DB INSERT (note the actual string variable for the stored proc is defined as a private string at the top of the class):

    public void SaveCustomer(CustomerDTO custDTO)
    {
        using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString))
        {
            db.Execute(saveCustSp, custDTO, commandType: CommandType.StoredProcedure);
        }
    }

This all works fine but I am finding myself repeating the using block in every method in every repository. I have two real questions outlined below.

Is there a better approach which I could be using perhaps somehow using a BaseRepository class which every other Repository inherits from and the Base would implement the instantiation of the DB connection?

Would that still work ok for multiple concurrent Users on the system?

Aucun commentaire:

Enregistrer un commentaire