Reputation: 199
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.
Upvotes: 5
Views: 5255
Reputation: 1532
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;
}
}
}
Upvotes: 1
Reputation: 12805
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");
Upvotes: 10