【问题标题】:Autofac - Mvc 5 beta - DependencyResolver fails to get typeAutofac - Mvc 5 beta - DependencyResolver 无法获取类型
【发布时间】:2013-07-12 13:13:28
【问题描述】:

我刚刚将一个 MVC 4 项目转换为 MVC 5 beta(并将一个 Web Api 项目转换为 Web Api 2),我遇到了一些问题,DependencyResolver 无法解析我需要的类。

这是我要解决的类:

 public class GetPartsQueryValidationHandler
    : IQueryValidationHandler<GetPartsQuery, Part[]>
{
    ...
}

这是我在 Bootstrapper.cs 中使用 Autofac 注册它的方法(我在两个项目中都这样做):

 builder.RegisterAssemblyTypes(dataAccessAssembly)
               .AsClosedTypesOf(typeof(IQueryValidationHandler<,>))
               .InstancePerHttpRequest(); //..PerApiRequest in Web Api

我还在两个项目中注册了 DependencyResolver:

在 Mvc 项目中:

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

在 Web Api 项目中:

 GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

然后在第三个项目中,我调用以下方法来解析引用:

 var handlerType = typeof(IQueryValidationHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
 dynamic handler = DependencyResolver.Current.GetService(handlerType);

但这给了我一个空的handler

我需要以某种方式解决该类。

【问题讨论】:

    标签: asp.net asp.net-web-api autofac asp.net-mvc-5


    【解决方案1】:

    好的,我想出了如何替换 DependencyResolver...当构造函数依赖是一个选项时,这似乎是一种反模式。我之前不知道如何让它工作,但我又试了一次,看起来你只需要一个 IComponentContext 构造函数参数,Autofac 默认会处理它:

    public class DefaultQueryBus : IQueryBus
    {
        private readonly IComponentContext componentContext;
    
        public DefaultQueryBus(IComponentContext componentContext)
        {
            this.componentContext = componentContext;
        }
    
        public IEnumerable<ValidationResult> Validate<TResult>(IQuery<TResult> query)
        {
            var handlerType = typeof(IQueryValidationHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
            dynamic handler = this.componentContext.Resolve(handlerType); //Good
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 2015-09-07
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多