2017-03-24 61 views
1

我正在使用Mediatr 3的管道行爲的新功能。問題是,當我將它們連接到Mediatr時,每調用一次.Send()都會拋出異常(System.InvalidCastException)。處理程序被調用的很好,但是當管道行爲被調用的時候,它會失敗。嘗試在ASP.NET Core中使用IPipelineBehavior - 獲取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) 

如果我註釋掉爲我的行爲佈線,我的處理程序被調用的很好。而其他應用程序似乎工作。

我做錯了什麼?

回答

0

我想通了。

原來,在我的應用程序的另一個命名空間中創建了一個與我的行爲同名的內部類。可能是「生成類定義」的結果。

刪除生成的類清除了問題。