0

PROBLEM DESCRIPTION

I have an interface definition IFoo<TBar> : IFoo and a method CreateFooUsingBarType(Type barType). I need the method to resolve an IFoo<TBar> using a dependency injection tool given a specified System.Type instance that defines TBar. Don't ask how I ended up here. I am stuck within these boundaries.

EXAMPLE

public IFoo CreateFooUsingBarType(Type barType)
{
    var iocScope = GetScope();

    // TODO: Create a System.Type for IFoo<TBar>
    // where TBar is barType. Blarghity blargh.
    var fooType =  (Type)null;

    return iocScope.Resolve(fooType);
}

I've tried mucking around with TypeBuilder but I'm getting the sense that it's overkill for this. Does .NET expose a different API for achieving this?

Thanks in advance.

AdamStone
  • 138
  • 1
  • 8

1 Answers1

3

You can use the MakeGenericType method:

var fooType = typeof(IFoo<>).MakeGenericType(barType);
BotondF
  • 190
  • 1
  • 11