尝试将IPipelineBehavior与ASP.NET Core一起使用 - 获取System.InvalidCastException

时间:2017-03-24 13:38:11

标签: mediatr

我使用Mediatr 3的管道行为新功能。问题是,当我将它们连接到Mediatr时,每次.Send()调用都会抛出异常(System.InvalidCastException)。处理程序被称为正常,但是当它调用管道行为的时间时,它就会失败。

这是我的设置:

    services.AddScoped<SingleInstanceFactory>(p => t => p.GetRequiredService(t));
    services.AddScoped<MultiInstanceFactory>(p => t => GetRequiredServices(p,t));
    services.AddScoped(typeof( IPipelineBehavior<, >), typeof(AddSessionBehavior<, >));
    services.AddMediatR();

我的行为:

public class AddSessionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    {
        IHttpContextAccessor Accessor;
        public AddSessionBehavior(IHttpContextAccessor anAccessor)
        {
            this.Accessor = anAccessor;
        }
        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next)
        {

            var response = await next();
            return response;

        }
    }

当我通过调解员发送第一条消息时,我得到:

System.InvalidCastException occurred
  HResult=0x80004002
  Message=Object cannot be stored in an array of this type.
  Source=<Cannot evaluate the exception source>
  StackTrace:
   at System.Array.InternalSetValue(Void* target, Object value)
   at System.Array.SetValue(Object value, Int32[] indices)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitClosedIEnumerable(ClosedIEnumerableCallSite closedIEnumerableCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at MediatR.ServiceCollectionExtensions.GetRequiredServices(IServiceProvider provider, Type serviceType)
   at MediatR.Internal.RequestHandlerImpl`2.GetPipeline(TRequest request, RequestHandlerDelegate`1 invokeHandler, MultiInstanceFactory factory)
   at MediatR.Internal.RequestHandlerImpl`2.Handle(IRequest`1 request, CancellationToken cancellationToken, SingleInstanceFactory singleFactory, MultiInstanceFactory multiFactory)
   at MediatR.Mediator.Send[TResponse](IRequest`1 request, CancellationToken cancellationToken)
   at Merlin.Web.Controllers.CourseController.Add(CourseAddVM model) 

如果我为我的行为发表评论,我的处理程序会被称为罚款。其余的应用程序似乎工作。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我明白了。

事实证明,在我的应用程序的不同命名空间中创建了一个与我的行为同名的内部类。可能是“生成类定义”的结果。

删除生成的类可以解决问题。