0

I have several objects that implement an interface, and several repositories that perform CRUD operations these objects.

I'm given a GUID and I don't know which class the object is, but it's in one of them, and am using the repository to get the object by its GUID.

The repos return different types.

class Obj1 : IInterface
{
}
class Obj2 : IInterface
{
}
class Obj3 : IInterface
{
}
var repo1 = new Repo1();
var repo2 = new Repo2();
var repo3 = new Repo3();
Obj1 obj = repo1.Get(someGuid);
if (obj != null) 
{ 
 // use obj
}
else 
{
 Obj2 obj2 = repo2.Get(someGuid);
 if (obj2 != null) 
 { 
 // use obj2
 }
 else 
 {
 Obj3 obj3 = repo3.Get(someGuid); 
 if (obj3 != null) 
 { 
 // use obj3
 }
 else 
 {
 // Check another repository
 }
 }
}

This gets more tedious as more objects implement that interface.

Is there a pattern for this or a nicer way of doing it?

asked Feb 21, 2018 at 10:35
2
  • I have to wonder if a better 'if block' really helps you. Maybe there is a way you can know which repo to check Commented Feb 21, 2018 at 11:01
  • Pretending objects can be stored in a database never ends well regardless of what API you put in front of the database. Commented Oct 23, 2019 at 15:19

1 Answer 1

1

V2 answer, based on extra info supplied.

Since Repo1, Repo2 etc all have a Get that returns an IInterface, then you can use Func delegates and linq to simplify this:

var repo1 = new Repo1();
var repo2 = new Repo2();
var repo3 = new Repo3();
var repoGetters = new List<Func<GUID, IInterface>>
{
 repo1.Get,
 repo2.Get,
 repo3.Get
};
var obj = repoGetters.First(func => func(someGuid) != null);

obj will then be of type IInterface.

The above assumes a match is guaranteed. If not, replace First with FirstOrDefault and test obj for null to see if a match occurred.

answered Feb 21, 2018 at 10:49
4
  • That would've been a good answer but they don't implement a common interface :( Commented Feb 21, 2018 at 11:03
  • @Graham, Do the Gets return a common type? Commented Feb 21, 2018 at 11:04
  • No the objects returned are different types but the objects implement the same interface Commented Feb 21, 2018 at 11:05
  • @Graham, answer updated therefore to provide a solution. Commented Feb 21, 2018 at 11:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.