GithubHelp home page GithubHelp logo

jbogard / mediatr.extensions.microsoft.dependencyinjection Goto Github PK

View Code? Open in Web Editor NEW
327.0 20.0 89.0 153 KB

MediatR extensions for Microsoft.Extensions.DependencyInjection

License: MIT License

PowerShell 2.34% C# 97.66%

mediatr.extensions.microsoft.dependencyinjection's Introduction

mediatr.extensions.microsoft.dependencyinjection's People

Contributors

ardalis avatar dpaquette avatar ewoutdboer avatar expecho avatar ffje avatar henkmollema avatar jamesrandall avatar jbogard avatar joaomatossilva avatar ljani avatar markmillercc avatar noocyte avatar remcoros avatar steventcramer avatar vasilisgaitanidis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mediatr.extensions.microsoft.dependencyinjection's Issues

Issue with the example.

This line on the example is not working.
this is the error ->

this line ->  IServiceCollection services = new ServiceCollection();
The type or namespace name 'ServiceCollection' could not be found

How to register generic envelope?

I need send message wrapped in envelope.

mediatr.Send(new Envelope(new Jing(),new Dictionary<string,object>()).ToGenericEnvelope()

message can handled by:

  public class JingHandler : AsyncRequestHandler<Envelope<Jing>>
    {
        private readonly TextWriter _writer;

        public JingHandler(TextWriter writer)
        {
            _writer = writer;
        }

        protected override Task Handle(Envelope<Jing> request, CancellationToken cancellationToken)
        {
            return _writer.WriteLineAsync($"--- Handled Jing: {request.Message.Message}, no Jong");
        }
    }

but when I add GenericPipelineBehaviour, di cannot handle this and throw exception.

public class GenericPipelineBehavior<TRequest, TResponse> : IPipelineBehavior<Envelope<TRequest>, TResponse>
  {
      private readonly TextWriter _writer;

      public GenericPipelineBehavior(TextWriter writer)
      {
          _writer = writer;
      }

      public async Task<TResponse> Handle(Envelope<TRequest> request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
      {
          await _writer.WriteLineAsync("-- Handling Request");
          var response = await next();
          await  _writer.WriteLineAsync("-- Finished Request");
          return response;
      }
  }
System.InvalidCastException : Object cannot be stored in an array of this type.
   at System.Array.InternalSetValue(Void* target, Object value)
   at System.Array.SetValue(Object value, Int32 index)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitIEnumerable(IEnumerableCallSite enumerableCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass22_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
public class Envelope<TMessage> //Used by handlers
    {
        private readonly Envelope _envelope;

        public Envelope(Envelope envelope)
        {
            _envelope = envelope ?? throw new ArgumentNullException(nameof(envelope));
        }

        public TMessage Message => (TMessage)_envelope.Message;
        public long Position => (long)_envelope.Metadata["Position"];
  
        public IReadOnlyDictionary<string, object> Metadata => _envelope.Metadata;
    }

    public class Envelope //Used by dispatchers
    {
        //Note we could precompute these factories for all known message types.
        private static readonly ConcurrentDictionary<Type, Func<Envelope, object>> Factories =
            new ConcurrentDictionary<Type, Func<Envelope, object>>();

        public Envelope(object message, IReadOnlyDictionary<string, object> metadata)
        {
            Message = message ?? throw new ArgumentNullException(nameof(message));
            Metadata = metadata ?? throw new ArgumentNullException(nameof(metadata));
        }

        public object Message { get; }
        public IReadOnlyDictionary<string, object> Metadata { get; }

        public object ToGenericEnvelope()
        {
            var factory = Factories
                .GetOrAdd(Message.GetType(), typeOfMessage =>
                {
                    var parameter = Expression
                        .Parameter(typeof(Envelope), "envelope");
                    return Expression
                        .Lambda<Func<Envelope, object>>(
                            Expression.New(
                                typeof(Envelope<>)
                                    .MakeGenericType(typeOfMessage)
                                    .GetConstructors()
                                    .Single(),
                                parameter),
                            parameter)
                        .Compile();
                });
            return factory(this);
        }
    }

Help Required

Im trying to use MediatR across multiple class libraries as the following :

- Project 1 >> Raise INotification<EventTest>
- Project 2 >> Handle INotificationHandler<EventTest>
- Project 3 >> Handle INotificationHandler<EventTest>

if i create handler withing the same class library it works well, however Project 2 and 3 handlers are never triggered, i register all the above using Microsoft DI and Scrutor
any help plz ?

Open generic service type 'MediatR.Pipeline.IRequestPreProcessor`1[TRequest]' requires registering an open generic implementation type

I tried working around #28 by implementing my behavior as a pre-processor instead (the actual behavior is validation, so this fits well with my use-case anyway), but now the application fails to start, with the following error:

Unhandled Exception: System.ArgumentException: Open generic service type 'MediatR.Pipeline.IRequestPreProcessor`1[TRequest]' requires registering an open generic implementation type.
Parameter name: descriptors
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.Populate(IEnumerable`1 descriptors)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory..ctor(IEnumerable`1 descriptors)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at Web.Program.BuildWebHost(String[] args) in C:\Work\my-project\Web\Program.cs:line 21
   at Web.Program.Main(String[] args) in C:\Work\my-project\Web\Program.cs:line 17

The service registration is, as before, just services.AddMediatR(typeof(FooHandler)), and the implementation of the pre-processor is

public class FooPreProcessor : IRequestPreProcessor<FooCommand>
{
    public Task Process(FooCommandrequest, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }
}

Am I missing something here, or is this the same problem as #12?

Service registration crashes when concrete type is generic

public class SomeHandler<T> : INotificationHandler<Ping>
{
    public Task Handle(Ping notification, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }
}

will fail, because will be "registered" as "open generic concrere type" at line 163
matches.ForEach(match => services.AddTransient(@interface, match));

Maybe it's worth looking services for registered types SomeHandler with closed T? Something like

var matches = concretions
    .Where(t => t.CanBeCastTo(@interface))
    .ToList();

foreach (var match in matches)
{
    if (match.IsGenericTypeDefinition)
    {
        foreach (var serviceDescriptor in services.ToList())
        {
            if (serviceDescriptor.ImplementationType != null)
            {
                var implType = serviceDescriptor.ImplementationType;
                if (implType.IsGenericType && implType.GetGenericTypeDefinition() == match)
                {
                    services.AddTransient(@interface, implType);
                }
                continue;
            }

            if (serviceDescriptor.ImplementationFactory != null)
            {
                var implType = serviceDescriptor.ImplementationFactory.Method.ReturnType;
                if (implType.IsGenericType && implType.GetGenericTypeDefinition() == match)
                {
                    services.AddTransient(@interface, implType);
                }
            }
        }
    }
    else
    {
        if (addIfAlreadyExists)
            services.AddTransient(@interface, match);
        else
        {
            if (IsMatchingWithInterface(match, @interface))
                services.TryAddTransient(@interface, match);
        }
    }
}

Of course this will require registration services.AddMediatR(...); after the rest, but it's better than an error

ps: I thought that for such a registration exists the code but I can not think of a situation when this code is executed

ASP.NET CORE Unable to resolve IMediator from IHostedService

I have a back ground Service which implement IHostedService. I am using mediatr in it to send commends and notification to different objects from this hosted service.

public class Startup
{
........
public void ConfigureServices(IServiceCollection services)
{
........
services.AddMediatR(typeof(Startup).GetTypeInfo().Assembly);
.....

On runtime, i get this error:
System.InvalidOperationException: 'Cannot consume scoped service 'MediatR.IMediator' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.'

In ASP.Net Core 1.0 project, notification is handled twice in handler

this duplicate handling was causing the same email to be sent twice to the same person...

I fixed it in our project removing the MediatR.Extensions.Microsoft.DependencyInjection package and reverting to the old way of registering MediatR... basically, something like this:

var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterSource(new ContravariantRegistrationSource());
containerBuilder.RegisterAssemblyTypes(typeof(IMediator).Assembly).AsImplementedInterfaces();
containerBuilder.RegisterAssemblyTypes(typeof(Startup).Assembly).AsImplementedInterfaces();
containerBuilder.Register<SingleInstanceFactory>(ctx =>
{
    var c = ctx.Resolve<IComponentContext>();
    return t => c.Resolve(t);
});

containerBuilder.Register<MultiInstanceFactory>(ctx =>
{
    var c = ctx.Resolve<IComponentContext>();
    return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
});

How can I provide you more information to see if this is a bug or we're not using/registering MediatR correctly?

What service lifetime for handlers?

Please indicate service lifetime for handlers detected by scanning: Singleton, Scoped or Transient?

I assuming transient, because makes most sense?

(Could be helpful as one-liner on main page.)

Unhandled exception when resolving open generic IRequestExceptionHandler implementation

I'm trying to define essentially a catch-all request exception handler independent of message types, something like this:

public class GenericExceptionHandler<TRequest, TResponse> : IRequestExceptionHandler<TRequest, TResponse>

However, MS DI throws when MediatR is trying to get errors handlers:

System.ArgumentException: The number of generic arguments provided doesn't equal the arity of the generic type definition.
Parameter name: instantiation
   at System.RuntimeType.MakeGenericType(Type[] instantiation)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateOpenGeneric(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type serviceType)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at MediatR.Pipeline.RequestExceptionProcessorBehavior`2.GetExceptionHandlers(TRequest request, Type exceptionType, MethodInfo& handleMethodInfo)
   at MediatR.Pipeline.RequestExceptionProcessorBehavior`2.<Handle>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MediatR.Pipeline.RequestExceptionActionProcessorBehavior`2.<Handle>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at MediatR.Pipeline.RequestExceptionActionProcessorBehavior`2.<Handle>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MediatR.Pipeline.RequestPostProcessorBehavior`2.<Handle>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MediatR.Pipeline.RequestPreProcessorBehavior`2.<Handle>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MediatR.Extensions.Microsoft.DependencyInjection.Tests.PipelineTests.<>c__DisplayClass23_0.<<Should_pick_up_base_exception_behaviors>b__0>d.MoveNext() in C:\p\sym\MediatR.Extensions.Microsoft.DependencyInjection\test\MediatR.Extensions.Microsoft.DependencyInjection.Tests\PipelineTests.cs:line 457
   at Shouldly.Should.CompleteIn(Task actual, TimeSpan timeout, Func`1 customMessage, String what)
   at Shouldly.Should.CompleteIn(Task actual, TimeSpan timeout, Func`1 customMessage)
   at Shouldly.Should.RunAndWait(Func`1 actual, TimeSpan timeoutAfter, Func`1 customMessage)
   at Shouldly.Should.ThrowInternal[TException](Func`1 actual, TimeSpan timeoutAfter, Func`1 customMessage, String shouldlyMethod)

The only way to make it work that I found is to have the handler explicitly define the third generic parameter.

This works:

public class GenericExceptionHandler<TRequest, TResponse, TException> : IRequestExceptionHandler<TRequest, TResponse, TException> where TException : Exception

These don't:

public class GenericExceptionHandler<TRequest, TResponse> : IRequestExceptionHandler<TRequest, TResponse, Exception>
public class GenericExceptionHandler<TRequest, TResponse> : IRequestExceptionHandler<TRequest, TResponse>

Perhaps this is a limitation of MS DI, but at least MediatR makes this partially closed interface available IRequestExceptionHandler<TRequest, TResponse> so it is still possible to shoot oneself in the foot.
Perhaps I'm doing something wrong?

Change AddTransient to TryAddTransient?

Calling...

services.AddMediatR()

..overwrites any mediators that may have been previously added in say a TestServer since adding any mocked services is called before Startup.ConfigureServices()

Could AddTransient() be switched to TryAddTransient?

Error when using MediatR DI NuGet library with TestServer in integration tests

I am getting the error below when running an API integration test using the Microsoft.AspNetCore.TestHost TestServer object. I don't get this error when I pull down the ServiceCollectionExtensions.cs code from the library to reproduce it in a test app. I am new to all this so I hope this isn't just a stupid question. But since I cannot reproduce the issue pulling down the code, is it a problem with the nuget package? Just wanted to give you a heads up for others that might run into this issue using the nuget package.

Thank you for all the libraries and support you give to the community, Jimmy.

using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Xunit;

namespace TestServerExample.IntegrationTests
{
    public class ApiTests
    {
        private readonly TestServer _server;
        private readonly HttpClient _client;
        public ApiTests()
        {
            // Arrange
            _server = new TestServer(new WebHostBuilder()
                .UseStartup<Startup>());
            _client = _server.CreateClient();
        }

        [Fact]
        public async Task ReturnHelloWorld()
        {
            // Act
            var response = await _client.GetAsync("api/values/1");
            response.EnsureSuccessStatusCode();

            var responseString = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal("value",
                responseString);
        }
    }
}

System.IO.FileLoadException
Could not load file or assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
   at TestServerExample.Startup.ConfigureServices(IServiceCollection services)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder)
   at TestServerExample.IntegrationTests.ApiTests..ctor() in C:\Projects\TestServerExample\TestServerExample.IntegrationTests\ApiTests.cs:line 21

Mediatr don't know publish to singleton registrations for INotificationHandler<T>

When we use singleton service for handle INotificationHandler, mediatr.publish(T) method make new instance of service every publish.

Its not good behaviors, we need make only one instance (singleton) of our service. but currently we can't do it because we use mediatr, and mediatr don't know how to publish message to singleton

Please fix this issue ASAP

Add Notify as Singleton not working

       services.AddMediatR();

        services.AddSingleton<INotificationHandler<CanalBody>, RabbitHandler>();

I add singleton after AddMediratR but not woking

Support for MediatR 5.0.0?

I have a very simple setup with ASP.NET Core DI, and the latest versions of MediatR and this package, and I'm getting

Application startup exception: System.TypeLoadException: Could not load type 'MediatR.SingleInstanceFactory' from assembly 'MediatR, Version=5.0.0.0, Culture=neutral, PublicKeyToken=null'.

I'm literally only doing

services.AddMediatR(typeof(ARequestHandlerInADifferentProject));

to make this happen. But looking at the source tree for MediatR, it seems that the SingleInstanceFactory doesn't exist anymore (so it's not so strange that this package can't find it). Does this package need an update to work with 5.0?

Can I help?

Cannot instantiate implementation type

using MediatR;
using System.Collections.Generic;
using System.Linq;
using TSClean.BusinessEntities.Infrastructure;
using TSClean.Repository;

namespace TSClean.BusinessLogic
{
    public class GetAll<T> : IRequest<IEnumerable<T>>
    {        
    }

    public class GetAllHandler<T> : IRequestHandler<GetAll<T>, IEnumerable<T>> where T : EntityBase
    {
        private readonly TSCleanRepositories _db;

        public GetAllHandler(TSCleanRepositories db)
        {
            _db = db;
        }

        public IEnumerable<T> Handle(GetAll<T> message)
        {
            return _db.GetRepository<T>().AsEnumerable().Where(t => !t.DateDeleted.HasValue).ToList();
        }
    }
}

using .NET Core and Mediatr Extensions.

Container throws Exception: Cannot instantiate implementation type.
Why?

Asp.Net Core always returns the same instance for scoped services

The Asp.Net Core is resolving scoped dependencies of a handler as singleton. I created a test to demonstrate the problem.

The SimpleInjector faced a similar issue.

I was able to fix this in my project by adding this code:

services.AddMediatR(typeof(Startup));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<SingleInstanceFactory>(p =>
{
    return t =>
    {
        var httpContextAccessor = p.GetRequiredService(typeof(IHttpContextAccessor)) as IHttpContextAccessor;
        return httpContextAccessor.HttpContext.RequestServices.GetRequiredService(t);
    };
});

AddMediatr + Autofac.AsImplementedInterfaces doubles notification handler registrations

Using autofac to load by type scanning doubles the handlers registrations. Repro:

using System;
using System.Linq;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace AutofacMediatRTest
{
    public class Startup
    {
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMediatR();

            //autofac takeover
            var builder = new ContainerBuilder();
            builder.Populate(services);

            builder.RegisterAssemblyTypes(typeof(Startup).Assembly)
                //.Except<NotificationSample.Handler>()
                .AsImplementedInterfaces();

            return new AutofacServiceProvider(builder.Build());
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                var med = context.RequestServices.GetService<IMediator>();
                var x = context.RequestServices
                    .GetServices<INotificationHandler<NotificationSample.Event>>();
                await context.Response.WriteAsync($" handlers# = {x.Count()}");
                await med.Publish(
                    new NotificationSample.Event() { Code = "C1", Description = "one arbitrary event" });
            });
        }
    }

    public class NotificationSample
    {
        public class Event : INotification
        {
            public string Description { get; set; }
            public string Code { get; set; }
        }

        public class Handler : NotificationHandler<Event>
        {
            protected override void Handle(Event notification)
            {
                Console.WriteLine($"code:{notification.Code} desc:{notification.Description}");
            }

        }
    }
}

The .Except if uncommented solves the issue by not registering the handler through autofac.

Handler of base type is not being executed when handler of derived type is not executed

I traced this issue to src\MediatR\Internal\NotificationHandlerWrapper.cs: line 20 where the serviceFactory is not returning the base handler type in the case of publishing DerivedNotification2

Example

public static class Program
{
    public static async Task Main(string[] args)
    {
        ServiceCollection services = new ServiceCollection();

        services.AddMediatR(Assembly.GetEntryAssembly());

        ServiceProvider provider = services.BuildServiceProvider();

        IMediator m = provider.GetRequiredService<IMediator>();

        await m.Publish(new DerivedNotification1());
        await m.Publish(new DerivedNotification2());
    }
}

public class DerivedNotification1Handler : INotificationHandler<DerivedNotification1>
{
    public Task Handle(DerivedNotification1 notification, CancellationToken cancellationToken)
    {
        Console.WriteLine($"DerivedNotification1 Handler");
        return Task.CompletedTask;
    }
}

public class BaseNotificationHandler : INotificationHandler<BaseNotification>
{
    public Task Handle(BaseNotification notification, CancellationToken cancellationToken)
    {
        Console.WriteLine("BaseNotification Handler");
        return Task.CompletedTask;
    }
}

public class BaseNotification : INotification { }
public class DerivedNotification1 : BaseNotification { }
public class DerivedNotification2 : BaseNotification { }

Expected

DerivedNotification1 Handler
BaseNotification Handler
BaseNotification Handler

Actual

DerivedNotification1 Handler
BaseNotification Handler

AddMediatR() not finding handlers in referenced libraries

In my asp.net core project, my handlers are located in a library that is referenced by main project. At the point where parameterless AddMediatR is called, this library is not loaded to AppDomain yet, so AddMediatR() cannot register those handlers.

Is this by design and I should specify explicitly the assemblies where handlers are located?

IRequestPreProcessor fired twice for all requests

This has been driving me mad and I thought it was my implementation:

...
collection.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPreProcessorBehavior<,>));
collection.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPerformanceBehavior<,>)); // Custom pipeline
collection.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestValidationBehavior<,>)); // Custom pipeline
collection.AddMediatR(...);
...

What is happening with 6.0.1 is that the PreProcessorBehavior is firing twice for every single request. This does not happen on every version between 5.0.0 and 6.0.0 exclusively.

Make ServiceCollectionExtensions.AddMediatRClasses public

Use case: message handlers are in different projects (plugins), each having its own AddXXX method for single line configuration in the hosting project. The hosting project will not pass any assembly references to MediatR, as plugin registration is separated from infrastructure setup.

Can't register PreProcessor

Not sure if I'm doing something wrong here, but I have a Pre Processor defined as:

public class RunPreProcessor : IRequestPreProcessor<EndRunCommand>

which throws the following error when calling .AddMediatR():

Open generic service type 'MediatR.Pipeline.IRequestPreProcessor`1[TRequest]' requires registering an open generic implementation type.'

If I comment out the class, the DI doesn't throw any errors. Registering manually works fine if I comment out .AddMediatR()

services.AddTransient<IRequestPreProcessor<EndRunCommand>, RunPreProcessor>();

If I register before .AddMediatR() it doesn't seem to skip already registered PreProcessors?

Changing to a generic handler seems to fix is. Is that the recommended approach?

public class RunPreProcessor<TCommand> : IRequestPreProcessor<TCommand>
{
    public Task Process(TCommand request, CancellationToken cancellationToken)
    {
        if (request is EndRunCommand command)
            return Process(command, cancellationToken);

        return Task.CompletedTask;
    }
}

Azure Function returns same instance for scoped service

I'm trying to use the new dependency injection features with Azure Functions where each invocation of the function should run within a dedicated scope. If I configure a scoped service, the instance injected into the function class is fine and changes each time the function is executed. However, the version injected into the request handler is always the same instance (singleton) and does not appear to be honoring the scope.

A sample project to repro the issue is attached: function_mediatr_test.zip

Release 5.2.0?

Any reason why 5.2.0 has been delayed?

The version was bumped in this PR #53 25 days ago.

Error When Using Microsoft.AspNetCore.TestHost

When my test project spins up TestServer and hits services.AddMediatR(typeof(Startup)) the following error is thrown: System.Reflection.ReflectionTypeLoadException: 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

The issue seems similiar to this Automapper DI Extensions issue

Versions:
Mediatr: 5.0.1
MediatR.Extensions.Microsoft.DependencyInjection: 5.0.2
AspNetCore: 2.0.8

Test Project
Microsoft.AspNetCore.TestHost: 2.1.1
xunit.runner.visualstudio: 2.3.1
Microsoft.NET.Test.Sdk: 15.7.0

Polymorphic dispatch not working

Hello, I'm having troubles using the polymorphic dispatch / generic variance feature.

This works (both messages are shown in the console):

namespace ConsoleApp2
{
    using System;
    using System.Globalization;
    using System.Threading;
    using System.Threading.Tasks;

    using MediatR;

    using Microsoft.Extensions.DependencyInjection;

    public static class Program
    {
        public static void Main()
        {
            var services = new ServiceCollection();

            services.AddMediatR();

            var provider = services.BuildServiceProvider(true);
            var scope = provider.CreateScope();

            var mediator = scope.ServiceProvider.GetService<IMediator>();
            var id = Guid.NewGuid();
            var ping = new Ping(id);

            mediator.Publish(ping).GetAwaiter().GetResult();

            Console.Write("Press any key to exit...");
            Console.ReadKey(true);
        }
    }

    public class Ping : INotification
    {
        public Ping(Guid id)
        {
            this.Id = id;
        }

        public Guid Id { get; }
    }

    public class Paddle : INotificationHandler<Ping>
    {
        public Task Handle(Ping notification, CancellationToken cancellationToken)
        {
            var value = string.Format(CultureInfo.InvariantCulture, "Ping: {0:D}", notification.Id);

            Console.WriteLine(value);

            return Task.CompletedTask;
        }
    }

    public class Logger : INotificationHandler<INotification>
    {
        public Task Handle(INotification notification, CancellationToken cancellationToken)
        {
            var type = notification.GetType();
            var value = string.Format(CultureInfo.InvariantCulture, "Notification received: {0}", type.FullName);

            Console.WriteLine(value);

            return Task.CompletedTask;
        }
    }
}

This does not work (no message is shown in the console):

namespace ConsoleApp
{
    using System;
    using System.Globalization;
    using System.Threading;
    using System.Threading.Tasks;

    using MediatR;

    using Microsoft.Extensions.DependencyInjection;

    public static class Program
    {
        public static void Main()
        {
            var services = new ServiceCollection();

            services.AddMediatR();

            var provider = services.BuildServiceProvider(true);
            var scope = provider.CreateScope();

            var mediator = scope.ServiceProvider.GetService<IMediator>();
            var id = Guid.NewGuid();
            var ping = new Ping(id);

            mediator.Publish(ping).GetAwaiter().GetResult();

            Console.Write("Press any key to exit...");
            Console.ReadKey(true);
        }
    }

    public interface IPing : INotification
    {
        Guid Id { get; }
    }

    public class Ping : IPing
    {
        public Ping(Guid id)
        {
            this.Id = id;
        }

        public Guid Id { get; }
    }

    public class Paddle : INotificationHandler<IPing>
    {
        public Task Handle(IPing notification, CancellationToken cancellationToken)
        {
            var value = string.Format(CultureInfo.InvariantCulture, "Ping: {0:D}", notification.Id);

            Console.WriteLine(value);

            return Task.CompletedTask;
        }
    }

    public class Logger : INotificationHandler<INotification>
    {
        public Task Handle(INotification notification, CancellationToken cancellationToken)
        {
            var type = notification.GetType();
            var value = string.Format(CultureInfo.InvariantCulture, "Notification received: {0}", type.FullName);

            Console.WriteLine(value);

            return Task.CompletedTask;
        }
    }
}

In the second example an interface has been introduced for the notification (IPing). The second example does not seem to work when using base classes too (public class Foo : INotification, public class Ping : Foo, public class Paddle : INotificationHandler<Foo>).

Adding services.Scan(scan => scan.FromAssembliesOf(typeof(IMediator), typeof(IPing)).AddClasses().AsImplementedInterfaces()); as shown in /samples/MediatR.Examples.AspNetCore/Program.cs doesn't seem to change anything.

Am I missing something?

It's a shame that AddRequiredServices isn't public via some means.

I am assembly scanning and registering all classes as implemented interfaces and ended up with notification handlers running twice.

My hotfix for now is to not use these extensions, but it'd be nice to have it for the boilerplate just without scanning for notifcation/request handlers.

Assembly Scanning is broken?

With the latest version the assembly scanning does not work for referenced assemblies anymore. I have to specifiy each assembly by my own. Is this really a good choice?

Service registration crashes when registering generic handlers

I want to register a generic handler, Handler<T>, that can handle requests of the generic type Request<T>, so I tried this:

public class MediatRConfigTests
{
    public class Request<T> : IRequest<IReadOnlyCollection<T>> { }

    public class Handler<T> : IAsyncRequestHandler<Request<T>, IReadOnlyCollection<T>>
    {
        public Task<IReadOnlyCollection<T>> Handle(Request<T> message)
        {
            return Task.FromResult(new ReadOnlyCollection<T>(new T[] { }) as IReadOnlyCollection<T>);
        }
    }

    [Fact]
    public void MediatRCanInstantiateGenericHandlers()
    {
        var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
        serviceCollection.AddMediatR(typeof(Handler<>));
        var serviceProvider = serviceCollection.BuildServiceProvider();
        var mediator = (IMediator)serviceProvider.GetService(typeof(IMediator));
        var result = mediator.Send(new Request<string>()); // an empty IReadOnlyCollection<string>
    }
}

However, that crashes on serviceCollection.BuildServiceProvider(), with an ArgumentException stating

Cannot instantiate implementation type 'XUnitTestProject1.MediatRConfigTests+Handler`1[T]' for 
service type 'MediatR.IAsyncRequestHandler`2[XUnitTestProject1.MediatRConfigTests+Request`1[T],System.Collections.Generic.IReadOnlyCollection`1[T]]'.

I wouldn't have been surprised if support for this depended on the IoC container, and this one happened not to support it, but the README explicitly states that this library "supports generic variance of handlers."

Am I doing something weird here, or is this a bug?

Mediatr won't respect singleton registrations for INotificationHandler<T>

Repo code:

class Program {
        static void Main(string[] args) {
            Console.WriteLine("Hello World!");

            var sc = new ServiceCollection();
            sc.AddSingleton(new Receiver());
            sc.AddMediatR(Assembly.GetExecutingAssembly());

            var sp = sc.BuildServiceProvider();

            var mediator = sp.GetService<IMediator>();
            mediator.Publish(new SuperEvent(1));
            mediator.Publish(new SuperEvent(2));
            mediator.Publish(new SuperEvent(3));
            
            Console.ReadLine();
        }
    }

    public class Receiver : INotificationHandler<SuperEvent> {
        public Receiver() {
            Console.WriteLine("Receiver created");
        }

        public Task Handle(SuperEvent notification, CancellationToken cancellationToken) {
            Console.WriteLine("received: " + notification.Id);
            return Task.CompletedTask;
        }
    }

    public class SuperEvent : INotification {
        public SuperEvent(int id) {
            Id = id;
        }

        public int Id { get; set; }
    }

The result is this:

Hello World!
Receiver created
Receiver created
received: 1
Receiver created
received: 2
Receiver created
received: 3

The expected result would be the Receiver object to be created only once :)

AddRequiredServices lifetime

Hey there,

I'm having a few issues using this library in an application where commands are received via HTTP calls but also via a messaging infrastructure.

Digging a bit in the code I found that current implementation of AddRequiredServices strongly relies on a scoped context while the acual configuration allows you to register a custom lifetime.

private static void AddRequiredServices(IServiceCollection services, MediatRServiceConfiguration serviceConfiguration)
{
   services.AddScoped<ServiceFactory>(p => p.GetService);
   services.AddScoped(typeof(IPipelineBehavior<,>), typeof(RequestPreProcessorBehavior<,>));
   services.AddScoped(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));
   services.Add(new ServiceDescriptor(typeof(IMediator), serviceConfiguration.MediatorImplementationType, serviceConfiguration.Lifetime));
}

I implemented a workaround by registering explicitely the components with another lifetime ; so my question is did I miss something or should the registered components also use the provided lifetime?

Regards,
Olivier

How can we specify the scope?

Currently, AddMediatR uses a "Scoped" scope. How can one use Singleton or Transient scope?
Is there a reason to use only Scoped?

ReflectionTypeLoadException on AddMediatR in Azure Web App

Using MediatR 6.0.0 and MediatR.Extensions..Microsoft.DependencyInjection 6.0.1.

Get the following exception on Startup when hosted in an Azure Web App when the Application Insights Site Extension is enabled:

Application startup exception: System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.
Could not load file or assembly 'Microsoft.ApplicationInsights, Version=2.9.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeAssembly.get_DefinedTypes()
   at MediatR.ServiceCollectionExtensions.<>c.<ConnectImplementationsToTypesClosing>b__9_0(Assembly a)
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at MediatR.ServiceCollectionExtensions.ConnectImplementationsToTypesClosing(Type openRequestInterface, IServiceCollection services, IEnumerable`1 assembliesToScan, Boolean addIfAlreadyExists)
   at MediatR.ServiceCollectionExtensions.AddMediatRClasses(IServiceCollection services, IEnumerable`1 assembliesToScan)
   at MediatR.ServiceCollectionExtensions.AddMediatR(IServiceCollection services, IEnumerable`1 assemblies, Action`1 configuration)
   at MediatR.ServiceCollectionExtensions.AddMediatR(IServiceCollection services)
   at Gaver.Web.Startup.ConfigureServices(IServiceCollection services) in d:\a\1\s\src\Gaver.Web\Startup.cs:line 64
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.ApplicationInsights, Version=2.9.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.
File name: 'Microsoft.ApplicationInsights, Version=2.9.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

Seems very related to this stackoverflow issue.

Maybe ConnectImplementationsToTypesClosing could use some kind of try-catch similar to the solutions for that issue, for the cases when an assembly isn't found for some reason?

Commands that derive from commands causes problems

I'm having an issue where a derived command is hitting the handler for the parent command. See jbogard/MediatR#229 for more details.

However I just realized that I also switched to using this package instead of rolling my own. So now I have services.AddMediatR(typeof(AssemblyAnchor));. Again see jbogard/MediatR#229 for more details.

Before I had:

public static class MediatorExtensions 
{ 
    public static IServiceCollection AddMediatorHandlers(this IServiceCollection services, Assembly assembly) 
    { 
        var classTypes = assembly.ExportedTypes.Select(t => t.GetTypeInfo()).Where(t => t.IsClass && !t.IsAbstract); 

        foreach (var type in classTypes) 
        { 
            var interfaces = type.ImplementedInterfaces.Select(i => i.GetTypeInfo()).ToList(); 

            foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRequestHandler<,>))) 
            { 
                services.AddTransient(handlerType.AsType(), type.AsType()); 
            } 

            foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAsyncRequestHandler<,>))) 
            { 
                services.AddTransient(handlerType.AsType(), type.AsType()); 
            } 

            foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRequestHandler<>))) 
            { 
                services.AddTransient(handlerType.AsType(), type.AsType()); 
            } 

            foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAsyncRequestHandler<>))) 
            { 
                services.AddTransient(handlerType.AsType(), type.AsType()); 
            } 
        } 

        return services; 
    } 
}
services.AddScoped<IMediator, Mediator>();
services.AddTransient<SingleInstanceFactory>(sp => t => sp.GetService(t));
services.AddTransient<MultiInstanceFactory>(sp => t => sp.GetServices(t));

services.AddMediatorHandlers(typeof(AssemblyAnchor).Assembly);

The above worked. Though I haven't tested it with MediatR v4. I used that with v3.

Perhaps this shed some light on the issue.

Possible bug closing open concrete types

I was trying to figure out what use case is adressed by the following section of code in the AddMediatRClasses method:

if ([email protected]())
{
    AddConcretionsThatCouldBeClosed(@interface, concretions, services);
}

I think it's supposed to try and close open generic concrete classes (like an open generic handler?) for every closed handler interface that was found. I wasn't able to find anything in the tests that resulted in the AddConcretionsThatCouldBeClosed method actually trying to add a registration.

I'm not sure it will ever try to do so as the CouldCloseTo method compares the number of generic type arguments of the closed type to the number of generic type arguments of the open type. Shouldn't it be comparing those to the number of generic type parameters? To get that the line above should I think be:

var concreteArguments = openConcretion.GetGenericArguments();

instead of:

var concreteArguments = openConcretion.GenericTypeArguments;

See http://stackoverflow.com/questions/19503905/type-generictypearguments-property-vs-type-getgenericarguments-method

It could be I'm reading this all wrong though, sometimes reflection does my head in :)

Do I need to register IPipelineBehaviors manually, or can this package handle it?

I have a class FooBehavior implemented as follows:

public class FooBehavior : IPipelineBehavior<FooCommand, string>
    {
        public Task<string> Handle(FooCommand request, CancellationToken cancellationToken, RequestHandlerDelegate<string> next)
        {
            throw new NotImplementedException();
        }
    }

and I'm registering MediatR with just services.AddMediatR(typeof(FooHandler)) (where FooHandler and FooBehavior live in the same assembly). When running the application and sending a FooCommand, I don't see the behavior at all - I was expecting the application to throw, but it just keeps going as if nothing happened.

I think the problem might be these lines:

var multiOpenInterfaces = new[]
{
typeof(IRequestPreProcessor<>),
typeof(IRequestPostProcessor<,>)
};

Should IPipelineBehavior<,> be among those interfaces? If not, what's the rationale behind leaving it out?

If you want it there, I can file a PR for the fix :)

Add ability to specify custom IMediator implementation

I wrote my custom IMediator implementation, and now I'd like to keep using MediatR.Extensions.Microsoft.DependencyInjection but specifying my custom implementation.

Something like

services.AddMediatR().Using<MyCustomMediator>();

Or even:

services.AddMediatR(cfg => cfg.Using<MyCustomMediator>());

By that, I will keep having all benefits of MediatR.Extensions.Microsoft.DependencyInjection, plus flexibility.

How to register duplicate handlers

Hi,

I have created a pull request in MediatR and MediatR.DI to handle registering duplicate IRequestHandlers.
jbogard/MediatR#320 and #46

To summarize the discussions:
You have for example a Package that you use that already contains MediatR Handling. Now you are creating your own Software depending on that Package and you want to overwrite these handlers because you want to modify this handling to more software specific handling.
At this moment, MediatR.DI just register the 2 handlers that are exactly the same like twins, only the implementation is different. So when you will call handlers request, it will call one of the 2 and you are not sure which one.

The change i made in these pull requests give you the opportunity to say which Handler can be overwritten. It was a solution, but not necessary the most satisfying one. For this case Jimmy asked me to open an Issue so we can discuss about it. What are the possibilities to implement this?

Thanks!

Notification Handler Type Registered Multiple Times

As per previously discussed in the following issue:
jbogard/MediatR#262

Registering multiple notification handler types from the same assembly for the same notification will result to multiple instance of same notification handler to be instantiated causing same event to be handled multiple times.

Maybe we should add a check to find are the current service type and implementation type already registered into the collection to prevent duplicate registering?

What's the right way to register IPipelineBehavior

Hi,

I have a PipelineBehavior like below
public class TracingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> { public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) { throw new NotImplementedException(); } }

Then I only add services.AddMediatR() into Startup.cs. But it doesn't work.
So I tried to inject it manually, like
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(TracingBehavior<,>));
But it still doesn't work...

May I know what is the right way to register it?

Thanks.

Adding services with 'Scoped' lifetime causes the lifetime of objects to be transient

Here is my code snippet:

services.Scan(scan => scan
			.FromAssembliesOf(typeof(MyService1))
			.FromAssembliesOf(typeof(MyService2))
			.AddClasses()
			.AsImplementedInterfaces()
			.WithScopedLifetime());

After wiring up, I examined "services" collection by debugging the code and realized that all classes exist in the assemblies hosting MyService1 and MyService2 are wired up as Transient instead of scoped.

Sign "MediatR.Extensions.Microsoft.DependencyInjection" assembly

It is better to have "MediatR.Extensions.Microsoft.DependencyInjection" signed in order to exclude warnings when it is referenced in signed assemblies, for example:

CSC : warning CS8002: Referenced assembly 'MediatR.Extensions.Microsoft.DependencyInjection, Version=6.0.1.0, Culture=neutral, PublicKeyToken=null' does not have a strong name.

Internal scoped handlers are not found

If an handler is declared with the internal visibility scope it does not get registered by the library.

example

internal class AccountListHandler : IRequestHandler<AccountListRequest, Result<IEnumerable<AccountResult>>>

Also one more question. Does this package helps registering also IRequestPreProcessor, IRequestPostProcessor and IPipelineBehavior types?

Multiple pre/post request processors for same request

Is it by design that only a single request pre/post processor is registered per request?

ConnectImplementationsToTypesClosing(typeof(IRequestPreProcessor<>), services, assembliesToScan, false);
ConnectImplementationsToTypesClosing(typeof(IRequestPostProcessor<,>), services, assembliesToScan, false);

I'd like to decorate my requests or responses with behavior by using multiple pre/post processors, however only one instance of the processor is invoked. In my opinion it would make sense to pass addIfAlreadyExists: true to ConnectImplementationsToTypesClosing for IRequestPreProcessor<> and IRequestPostProcessor<,>.

Question on ServiceFactory

Hi,

Question on the behaviour of the ServiceFactory, If resolving the service throws an ArgumentException it tries to build the class via reflection.

I have a situation where I have a pipeline and one of the steps failed to get resolved because of a dependency issue. What happens is, MediaR returns the pipeline but all the values where null because it couldn't build it via reflection.

The DI issue was swallowed and all I got from MediaR was a null reference exception

at MediatR.Internal.RequestHandlerWrapperImpl2.<>c__DisplayClass0_1.b__2()\r\n at MediatR.Internal.RequestHandlerWrapperImpl2.Handle(IRequest1 request, CancellationToken cancellationToken, ServiceFactory serviceFactory)\r\n at MediatR.Mediator.Send[TResponse](IRequest1 request, CancellationToken cancellationToken)\r\n

This was a pain because the issue wasn't obvious. What I have done as an interim solution is setup my own ServiceFactory impl, which is just a copy of yours without the catch.

Do you think that is ok, or is there a reason which I am unaware of what the catch block is suppose to handle.

services.AddScoped<ServiceFactory>(p => (type =>
            {
                try
                {
                    return p.GetService(type);
                }
                catch (ArgumentException)
                {
                    // Let's assume it's a constrained generic type
                    if (type.IsConstructedGenericType &&
                        type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                    {
                        var serviceType = type.GenericTypeArguments.Single();
                        var serviceTypes = new List<Type>();
                        foreach (var service in services)
                        {
                            if (serviceType.IsConstructedGenericType &&
                                serviceType.GetGenericTypeDefinition() == service.ServiceType)
                            {
                                try
                                {
                                    var closedImplType = service.ImplementationType.MakeGenericType(serviceType.GenericTypeArguments);
                                    serviceTypes.Add(closedImplType);
                                } catch { }
                            }
                        }

                        services.Replace(new ServiceDescriptor(type, sp =>
                        {
                            return serviceTypes.Select(sp.GetService).ToArray();
                        }, ServiceLifetime.Transient));

                        var resolved = Array.CreateInstance(serviceType, serviceTypes.Count);
                        
                        Array.Copy(serviceTypes.Select(p.GetService).ToArray(), resolved, serviceTypes.Count);

                        return resolved;
                    }

                    throw;
                }
            }));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.