动态创建Func主体

时间:2016-06-29 08:48:55

标签: c# reflection dependency-injection func

请参阅以下示例:

var factoryType = typeof(Func<>).MakeGenericType(someType);

container.RegisterPerRequest(someType, null, someType);

Func<object> factoryDelegate = () => container.GetInstance(someType, null); //this returns an object, hence the delegate type is Func<object>, but the required type is Func<SomeClass>

container.RegisterInstance(factoryType, null, factoryDelegate); //Not sure how to create factory delegate

我想创建一个函数体,其中将使用DI容器创建someType的实例。

我们的想法是配置DI容器,以便它可以将Func<SomeClass>注入其他类。

如何做到这一点?

1 个答案:

答案 0 :(得分:0)

刚刚投出结果:

Func<someType> factoryDelegate = () => container.GetInstance(typeof(someType), null) as someType;

或者创建一个方法(扩展会更好):

static Func<T> ResolveTypeDelegate<T>() where T : class
{
    return () => ResolveType<T>();
}

static T ResolveType<T>() where T : class
{
    return container.GetInstance(typeof(someType), null) as T;
}

用法:

Func<someType> factoryDelegate = ResolveTypeDelegate<someType>();