1

I just converted an MVC 4 project to MVC 5 beta (and a Web Api project to Web Api 2) and I'm having some issues with DependencyResolver not being able to resolve the class I need.

Here is the class I want to resolve:

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

Here is how I register it with Autofac in Bootstrapper.cs ( I do this in both projects):

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

I also register the DependencyResolver in both projects :

In Mvc Project:

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

In Web Api Project:

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

Then in a third project I call the following to resolve the reference:

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

But this gives me a null handler

I need to resolve that class somehow.

4

1 回答 1

0

好的,我想出了如何替换 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
    }
}
于 2013-07-14T17:05:14.357 回答