为什么在此代码中使用Func <t>?

时间:2015-04-22 13:22:58

标签: c# asp.net-mvc-4 dependency-injection delegates

我的一位同事发现了this代码,我们无法理解为什么需要_resolverThunk

代码摘要如下所示:

private Func<IDependencyResolver> _resolverThunk;

public SingleServiceResolver()
{
    _resolverThunk = () => DependencyResolver.Current;
}

private TService GetValueFromResolver()
{
   TService result = _resolverThunk().GetService<TService>();
   return result;
}

1 个答案:

答案 0 :(得分:4)

如果查看另一个内部构造函数,它会从参数中设置_resolverThunk。所以这很有道理。

 internal SingleServiceResolver(Func<TService> staticAccessor, TService defaultValue, IDependencyResolver resolver, string callerMethodName)
        : this(staticAccessor, defaultValue, callerMethodName)
 {
     if (resolver != null)
     {
            _resolverThunk = () => resolver;
     }
 }

否则,没有理由这样做。