· Chuck Conway · Programming  · 1 min read

Creating a Generic Type at Runtime

To use a runtime type with an IOC container like StructureMap to find a generic implementation, create the generic type using `MakeGenericType` and then retrieve the instance from the container using `_container.GetInstance(type)`.

To use a runtime type with an IOC container like StructureMap to find a generic implementation, create the generic type using `MakeGenericType` and then retrieve the instance from the container using `_container.GetInstance(type)`.

I have a type (at runtime), I want to use it with an IOC container (in this case StructureMap) to find a generic implementation using this type. How do I do that?

It’s simpler than you’d think:

Type genericType = typeof (AbstractValidator);
Type type = genericType.MakeGenericType(bindingContext.ModelType);

//Structure Map container
var instance = _container.GetInstance(type);

Share:
Back to Blog

Related Posts

View All Posts »
NVarchar Vs Varchar

NVarchar Vs Varchar

Each engineer defining a new string column decides: Do I use nvarchar or do I use varchar?

C# 8 - Nullable Reference Types

C# 8 - Nullable Reference Types

Microsoft is adding a new feature to C# 8 called Nullable Reference Types. Which at first, is confusing because all reference types are nullable… so how this different? Going forward, if the feature is enabled, references types are non-nullable, unless you explicitly notate them as nullable.