Reputation: 423
I am trying to implement an interface:
IListDto<TListDto>
And in my data repository, examine to see if a class implements that interface, and if so, call a method defined by that interface. I am not having much success. The details are as follows...
Thanks in advance for any help you can provide.
// I have a generic interface
public interface IListDto<TListDto>
{
TListDto ToListDto();
}
// This is an exaple of TListDto
public class ProductDto
{
public Guid ProductId { get; set; }
public string ProductName { get; set; }
}
// The product class implements IListDto<ProductDto>
public class Product : IListDto<ProductDto>
{
public Guid Id { get; set; }
public string ProductName { get; set; }
// ...other properties
// Implementation of IListDto<ProductDto>
public ProductDto ToListDto()
{
return new ProductDto()
{
ProductId = this.Id,
ProductName = this.ProductName
}
}
}
// I want to have a generic method in my Data Repository that can determine
// if a class implements TListDto. If it does, it converts the a list from
// List<TEntity> to List<TListDto> by calling the objects TListDto() implementation
public List<TListDto> ToDtoList(List<TEntity> list)
{
// The following is more or less pseudo-code as I am at a loss of where to take it from here...
// Test to see of TEntity implements IListDto
// ERROR 1: This test fails, even though TEntity implements IListDto
if (list is List<IListDto<TListDto>>)
{
// Yes, IListDto is implemented
// Cast list to List<IListDto>, the next line of code seems to work
List<IListDto<TListDto>> iList = list as List<TListDto>;
// ERROR 2: This line causes a nasty error message (System.NotSupportedException: Serialization
// and deserialization of 'System.Type' instances are not supported and should be avoided
/// since they can lead to security issues. Path: $.TargetSite.DeclaringType. etc...
var dtoList = iList.Select(s => s.ToListDto()).ToList();
return dtoList;
}
else
{
// No, throw not implemented error
throw new ApplicationException("Entity does not implement IListDto");
}
}
Upvotes: 0
Views: 62
Reputation: 8556
I am almost sure that the approach you are following isn't the most fit for the high level problem you are trying to solve, so I'd be very glad if you could explain exactly what that problem is, so I can give ou better advices.
Said that, the response to the question you are asking is:
I want to have a generic method in my Data Repository that can determine if a class implements TListDto. If it does, it converts the a list from List to List by calling the objects TListDto() implementation
try {
var iList = list.Cast<IListDto<TListDto>>();
return iList.Select(s => s.ToListDto()).ToList();
} catch (InvalidCastException) {
throw new ApplicationException("Entity does not implement IListDto");
}
Upvotes: 2