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?
-
I have to wonder if a better 'if block' really helps you. Maybe there is a way you can know which repo to checkEwan– Ewan2018年02月21日 11:01:34 +00:00Commented 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.Ian– Ian2019年10月23日 15:19:35 +00:00Commented Oct 23, 2019 at 15:19
1 Answer 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.
-
That would've been a good answer but they don't implement a common interface :(GMon– GMon2018年02月21日 11:03:29 +00:00Commented Feb 21, 2018 at 11:03
-
@Graham, Do the
Gets
return a common type?David Arno– David Arno2018年02月21日 11:04:50 +00:00Commented Feb 21, 2018 at 11:04 -
No the objects returned are different types but the objects implement the same interfaceGMon– GMon2018年02月21日 11:05:50 +00:00Commented Feb 21, 2018 at 11:05
-
@Graham, answer updated therefore to provide a solution.David Arno– David Arno2018年02月21日 11:29:29 +00:00Commented Feb 21, 2018 at 11:29