mercredi 19 juin 2019

How to register all open generic CQRS command and Query in Autofac

I'm implement CQRS, and want to Dispatch command And query. but when use AsClosedTypesOf for all IQueryHandler<,> in Autofac Module. I have an error.

When i use belong code every things is okey:

 builder.RegisterType<GetListQueryHandler> 
 ().As<IQueryHandler<GetListQuery, IEnumerable<StudentDto>>>()
          .InstancePerLifetimeScope();

but when use belong code i have an error:

 builder.RegisterAssemblyTypes(assembly)
.AsClosedTypesOf(typeof(IQueryHandler<,>))
.AsImplementedInterfaces().InstancePerLifetimeScope();

Error:

The requested service 'CQRSInPractice.Domain.Common.IQueryHandler2[[CQRSInPractice.Application.GetListQuery, CQRSInPractice.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[System.Collections.Generic.IEnumerable1[[CQRSInPractice.DTO.StudentDto, CQRSInPractice.DTO, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

My Code:

 public interface IQuery<TResult>{}
 public sealed class GetListQuery : IQuery<IEnumerable<StudentDto>>{}



 public interface IQueryHandler<in TQuery, TResult> where TQuery : IQuery<TResult>{}
 public sealed class GetListQueryHandler : IQueryHandler<GetListQuery, IEnumerable<StudentDto>>



 // Dispatch Method In Messages Class For Dispatching Query
 public async Task<T> DispatchAsync<T>(IQuery<T> query)
  {
    Type type = typeof(IQueryHandler<,>);
    Type[] typeArgs = { query.GetType(), typeof(T) };
    Type handlerType = type.MakeGenericType(typeArgs);

    dynamic handler = _context.Resolve(handlerType);
    return await ((Task<T>)handler.Handle((dynamic)query));
  }
  //Autofac Module
  protected override void Load(ContainerBuilder builder)
  {
    builder.RegisterType<Messages>().As<IMessages> 
    ().InstancePerLifetimeScope();
    var assembly = Assembly.GetExecutingAssembly();

   builder.RegisterAssemblyTypes(assembly)
   .AsClosedTypesOf(typeof(IQuery<>))
    .InstancePerLifetimeScope();

  builder.RegisterAssemblyTypes(assembly)
  .AsClosedTypesOf(typeof(IQueryHandler<,>))
    .InstancePerLifetimeScope();
  }
  //Test

  [Theory]
  [AutoData]
  public async Task is_correct_get_list_query_dispatch(string enrolledIn, int numberOfCourses)
 {
   var getListQuery = new GetListQuery(enrolledIn, numberOfCourses);
   var result = await _messages.DispatchAsync(getListQuery);
   result.Count().Should().Be(0);
 }

Aucun commentaire:

Enregistrer un commentaire