jeudi 26 mars 2015

Web API 2 response design issue

I'm having some design problems (I think) and are looking for advice/alternative solutions. I have some base classes and one interface.



public interface IBuildLinks
{
void BuildLinks(Uri root);
}

public abstract class AbstractModel : IBuildLinks
{
public void BuildLinks(Uri root)
{
}
}

public abstract class AbstractCollectionModel<T> where T : AbstractModel, IBuildLinks
{
public List<T> Items { get; set; }

public void BuildLinks(Uri root)
{
}
}


And some implementations of these classes:



public class AssortmentModel : AbstractModel
{
}

public class AssortmentCollectionModel : AbstractCollectionModel<AssortmentModel>
{
}


I have a filter that should call BuildLinks if the response is a type that implements IBuildLinks



public class BuildModelLinksFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext context)
{
var content = context.Response.Content as ObjectContent;
if (content == null)
{
return;
}

var type = content.ObjectType;

if (type.IsAssignableFrom(typeof(IBuildLinks)))
{
var value = (IBuildLinks)content.Value;
var root = context.Request.GetRootUrl();

value.BuildLinks(new Uri(root));
}
}
}


Unfortunately this does not work since derived types like AssortmentCollectionModel is not recognized as implementing IBuildLinks


If I slap the IBuildLinks interface on every derived class it does work. It feels like there is a better way to do this so I'm looking for suggestions on how to improve the code. Perhaps I could do this fundamentally different in some way?






Aucun commentaire:

Enregistrer un commentaire