user4266661
user4266661

Reputation:

Type Parameter Constraint Violation

I have two generic classes, defined in two different assemblies, with one deriving from the other. The parent has several generic constraints on the type parameters:

public abstract class CountyBulkImporter<TImport, TContext, TUser>
    : DatabaseBulkImporter<TImport, TContext, TUser>
    where TImport  : class
    where TContext : IdentityDbContext<TUser>, ICampaignContext
    where TUser    : IdentityUser

The derived class has what appears to be corresponding constraints, with the caveat that one of the generic parameters is specified explicitly (HistoricalBallotInfo for TImport):

public class BallotBulkImporter<TContext, TUser> 
    : CountyBulkImporter<HistoricalBallotInfo, TContext, TUser>
    where TContext : IdentityDbContext<TUser>, ICampaignContext
    where TUser    : IdentityUser

FYI, the ICampaignContext constraint is defined in a third, separate assembly.

I scan for the derived class at runtime (it's loaded dynamically to provide extensibility to the program in which it's included):

var junk = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany( x => x.GetTypes() )
    .ToList();

The scan triggers a ReflectionTypeLoadException:

GenericArguments[1], 'TContext', on 'Olbert.WebJobs.CountyBulkImporter`3[TImport,TContext,TUser]' violates the constraint of type parameter 'TContext'.

Upvotes: 0

Views: 953

Answers (1)

user4266661
user4266661

Reputation:

It turns out the problem was that a supporting assembly was not being loaded into the application (recall that part of the context is that I'm loading assemblies dynamically at run-time to provide extensibility).

Setting a reference to the missing support assembly caused it to be included in the app's bin directory, which made it available at run-time.

I'll chalk this one up to an obscure error message. The takeaway is, if you get that generic Type parameter violation error, and are loading assemblies dynamically, make sure you're loading all the support assemblies the dynamically-loaded assemblies expect.

Upvotes: 1

Related Questions