C# dapper map to interface

c# dapper

Question

Can i use C# dapper to do something like this:

IFoo bar = _dbConnection.Query<IFoo>("My query there");

Now I can't do it, due to not impelemented default parameterless constructor.

Is there some trick to honor gods of SOLID (especially spirits of Liskov Substitution Principle) or should i leave it as it is and map my data not to IFoo but to Foo?

I'm really worrying about respecting these SOLID stuff, but still don't know where i should do it, so looking for an advice for this concrete situation.

Accepted Answer

You need a concrete implementation of your class to instantiate. Internally, it has to do a create a new object. You can't create a new instance of an interface:

var foo = new IFoo(); // This won't build!

You can still cast your result to an interface, but you need a concrete type to build from the database.

IEnumerable<IFoo> foo = _dbConnection.Query<Foo>("My query there");

Popular Answer

One way to organise repository is to use private class objects for querying, but expose results as public interfaces.

Pulbic Model:

namespace MyProject.Foo.Model
{
    public interface IFoo
    {
        string Property1 { get; set; }
        string Property2 { get; set; }
    }

    public interface IFooRepository
    {
        IEnumerbale<IFoo> GetFoos();
    }
}

Query implementation with private class:

namespace MyProject.Foo.Repositories
{
    public class FooRepository: IFooRepository
    {
        private class Foo: IFoo
        {
            public string Property1 { get; set; }
            public string Property2 { get; set; }
        }

        public IEnumerbale<IFoo> GetFoos()
        {
            IEnumerable<IFoo> foo = _dbConnection.Query<Foo>("My query there");
            return foo;
        }
    }
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why