I have classes for entities like Ship
, Shampoo
, Horse
etc and each of them will have a manager class like ShipManager
, ShampooManager
, HorseManager
etc. All the manager classes implement IManager
and entities implement IEntity
.
Now I have a static function written just to save the entities which would look like:
public static bool Save<S, T>(S entity, string msg) where S : IEntity
where T : IManager<S>, new()
{
string possibleError;
switch (new T().Save(entity, out possibleError))
{
//---------------------
}
return true;
}
The inelegance here is that I have to call the Save
like Save<Radio, RadioManager>
etc. What I would love to have is something like this:
public static bool Save<T>(T entity, string msg) where T : IEntity
{
string possibleError;
switch ((/*find manager here*/).Save(entity, out possibleError))
{
//---------------------
}
return true;
}
There are few ways to do this, but I would love to have something that involves generics and type inference. I am thinking it would be good to couple the entity classes with corresponding manager classes by design to achieve some type safety as well.
Here is what I could do, with the help of an extension method:
public static bool Save<T>(this IManager<T> mgr, T entity, string msg) where T : IEntity
{
string possibleError;
switch (mgr.Save(entity, out possibleError))
{
//---------------------
}
return true;
}
So that I can call:
FooManager fMgr = new FooManager();
fMgr.Save(foo, "success");
But here I always need to instantiate the IManager
and then call the Save
method on its instance. I would love to avoid that much repetitive code and give the duty to a static function. How can I design the classes to have a relationship between IManager
and IEntity
so that manager of entity is automatically inferred?
Edit: Please note that I dont have the luxury to move the Save
method in manager class to entity class (which would have made life easier). Our entire design is based on one entity class and a corresponding manager class. So I am thinking of sticking to it.