Autofac:DependencyResolutionException FluentValidation.IValidator

时间:2018-02-12 19:37:52

标签: c# asp.net-web-api2 autofac fluentvalidation

除IValidator注射外,一切正常。

我收到如下错误:

  

Autofac.Core.DependencyResolutionException:'期间发生错误   激活特定注册。查看内部异常   详情。注册:Activator = SampleCommandHandler   (ReflectionActivator),服务=   [MyApp.Domain.Core.ICommandHandler`1 [[MyApp.Domain.SampleCommand,   MyApp.Domain,Version = 1.0.0.0,Culture = neutral,   PublicKeyToken = null]]],Lifetime =   Autofac.Core.Lifetime.CurrentScopeLifetime,Sharing = None,Ownership   = OwnedByLifetimeScope'

     

内部异常DependencyResolutionException:无   建设者发现   ' Autofac.Core.Activators.Reflection.DefaultConstructorFinder'在类型上   ' MyApp.Domain.SampleCommandHandler'可以用。调用   可用的服务和参数:无法解析参数   ' {FluentValidation.IValidator {1}} 1 [MyApp.Domain.SampleCommand])'

我的应用程序是Web API ...我的参考项目:https://github.com/Weapsy/Weapsy.CMS

1[MyApp.Domain.SampleCommand]
  sampleCommandValidator' of constructor 'Void
  .ctor(MyApp.Domain.ISampleRepository,
  FluentValidation.IValidator

层:

  

MyApp.Service.WebAPI

     

MyApp.Application

     

MyApp.Application.Core

     

MyApp.Domain

     

MyApp.Domain.Core

     

MyApp.Infrastructure.Data

我已经尝试了所有解决方案,但没有成功。救命啊!

1 个答案:

答案 0 :(得分:0)

我无法确定没有查看您的实际项目,但Weapsy示例应用程序依赖于以下事实:所有程序集(包括包含对IValidator接口的引用的域程序集)都通过使用每个程序集中的类或接口进行注册AutofacModule:

var infrastructureAssembly = typeof(AggregateRoot).GetTypeInfo().Assembly;
var domainAssembly = typeof(CreateSite).GetTypeInfo().Assembly;
var dataAssembly = typeof(IDataProvider).GetTypeInfo().Assembly;
var reportingAssembly = typeof(GetAppAdminModel).GetTypeInfo().Assembly;
var servicesAssembly = typeof(IMailService).GetTypeInfo().Assembly;

但是,根据您提供的修剪后的代码,看起来像验证程序所属的域程序集,未注册:

builder.RegisterAssemblyTypes(typeof(IDbFactory).GetTypeInfo().Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(IResolver).GetTypeInfo().Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(ISampleRepository).GetTypeInfo().Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(IService).GetTypeInfo().Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(ISampleService).GetTypeInfo().Assembly).AsImplementedInterfaces();

看起来在验证器程序集中注册类型可以使其工作:

builder.RegisterAssemblyTypes(typeof(SampleApplyCommand).GetTypeInfo().Assembly).AsImplementedInterfaces();

如果没有,请确保注册验证程序实现所在的程序集。

这种用于注册依赖项的模式可能非常不透明,很难说明注册了哪些依赖项,我建议您明确注册并使用Autofac模块在程序集之间拆分它们。