Wrapper Class?

Ronald Rex 1,666 Reputation points
2022-07-26T16:45:50.59+00:00

Can someone please give me an example a using an Interface inside of a class and what is the code below called? wrapping a class inside of another class? Thanks !!!!!

public IDbConnection CreateDatabaseConnection()
=> new SqlConnection(_connectionString);

public class DapperContext  
    {  
        private readonly IConfiguration _configuration;  
        private readonly string _connectionString;  
        public DapperContext(IConfiguration configuration)  
        {  
            _configuration = configuration;  
            _connectionString = _configuration.GetConnectionString("SqlConnection");  
        }  
        public IDbConnection CreateDatabaseConnection()  
            => new SqlConnection(_connectionString);  
              
  
          
    }  
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2022-07-26T17:03:19.17+00:00

    The code sample looks like standard asp.net dependency injection pattern. The _configuration variable is just a field within the DapperContext class.

    Fields (C# Programming Guide)

    The _configuration field implements IConfiguration. The implementation (code) can read asp.net configuration. This is simply part of asp.net configuration that comes with the framework.

    Configuration in ASP.NET Core

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Cristina Carrasco 1 Reputation point
    2022-07-26T18:58:10.013+00:00

    I see what is confusing you, so this line of code:

    public IDbConnection CreateDatabaseConnection()  => new SqlConnection(_connectionString);  
    

    It is just a method using lamba expresion and it is equivalent to:

     public IDbConnection CreateDatabaseConnection()  
     {  
            return new SqlConnection(_connectionString);  
     }  
    

    It is returning a Class ( SqlConnection) which should be implementing IDbConnection Interface, that's it.

    To answer your question if it is called:

    wrapping an interface in a class?

    Nop, that is just normal interface-class behavior from always. I mean you can use Interface as a "Type" instead of the class "Type" to make your method more "flexible", and It could help you if you create new implementations of the same interface or while you test the code.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.