Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnownType attribute cannot use type parameters

I have this Web Api controller action:

public Plant<TissueProductionLine> GetPlant(string plant, string range)
{
    return _repo.GetPlant(plant, range);
}

Firing this up I get this:

Type 'IGMProdLineDashboard.Models.TissueProductionLineGroup' with data contract name 'IGMProdLineDashboard.Models' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

Ok, no problem, I'll just decorate my Plant object with the [KnownType] attribute and specify the non-primitive property:

[KnownType(typeof(ProductionLineGroups<T>))]
public class Plant<T>: IPlant<T> where T : IProductionLine
{
    public Plant ()
    {
        ProductionLineGroups = new ProductionLineGroups<T>();
    }
    public ProductionLineGroups<T> ProductionLineGroups { get; set; }

Now I get a compile-time error:

'IGMProdLineDashboard.Models.ProductionLineGroups': an attribute argument cannot use type parameters

Re-reading the first message, it wants to know about the derived type: TissueProductionLineGroup

If I decorate my Plant object with this, everything works:

[KnownType(typeof(TissueProductionLineGroup))]

Obviously the implication here is my Plant now needs to know about all different kinds of production lines, which means I'll need to update the Plant whenever a new group is added.

Is there any way around this?

like image 560
Mister Epic Avatar asked May 07 '14 14:05

Mister Epic


1 Answers

Unfortunately, the error message isn't misleading you at all. Attributes cannot use generic type parameters. As far as I know, there is no way around the issue.

Jon Skeet formerly posted an answer on the matter and said that the C# team chose to add this restraint in order to keep the compiler code simpler, although there is no reason why the CLI cant represent generic attributes.

See: https://stackoverflow.com/a/294259/2394286

like image 91
astallaslions Avatar answered Oct 05 '22 00:10

astallaslions