Max Melnikov Max Melnikov - 3 months ago 41
ASP.NET (C#) Question

ASP.NET Core reflection di

I did settings for RabbitMQ, for example my extension:

public static class QueueExtension
{
public static IServiceCollection UseQueue<TQueue, TApiService>(this IServiceCollection services, string host, string login,
string password, string queue, IDictionary<string, object> arg) where TQueue : class, IEventHandler where TApiService : class, IService
{
if (services == null)
throw new ArgumentNullException("services");
return UseQueue<TQueue, TApiService>(services, typeof(TQueue), typeof(TApiService), host, login, password, queue, arg);
}

public static IServiceCollection UseQueue<T, Y>(this IServiceCollection services, Type queueType, Type apiServiceType, string host, string login,
string password, string queue, IDictionary<string, object> arg) where T : IEventHandler where Y: IService
{
if (services == null)
throw new ArgumentNullException("services");
if (queueType == null)
throw new ArgumentNullException("queueType");
if (apiServiceType == null)
throw new ArgumentNullException("apiServiceType");

var parametersQueueType = queueType
.GetConstructors()
.SelectMany(p=>p.GetParameters())
.Select(p=>p.ParameterType)
.ToList();

var parametersType = services
.Where(p => parametersQueueType.Select(z => z.FullName)
.Contains(p.ServiceType.FullName))
.ToList();

var parameters = new List<object>();

parametersType.ForEach(p =>
{
parameters.Add((Y)Activator.CreateInstance(p.ImplementationType));
});

var impl = (T)Activator.CreateInstance(queueType, parameters);

var queueService = new QueueServiceImpl(host, login, password, queue, arg);
queueService.ReceivedMessage += (sender, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
impl.MessageHandler(message);
};
queueService.Start();

return services;
}

}


I use it in
startup.cs
:

services.UseQueue<PrimaryEventHandlerImpl, IRsmService(
Configuration[AppConstants.HostPrimary],
Configuration[AppConstants.LoginPrimary],
Configuration[AppConstants.PasswordPrimary],
Configuration[AppConstants.QueuePrimary],
arg
);


But it wrong in all time do error in this line:

var impl = (T)Activator.CreateInstance(queueType, parameters);


Say that:


Constructor ontype
Monq.Core.Service.RSMModeGenerator.Services.PrimaryEventHandlerImpl
not found.


but this my
PrimaryEventHandlerImpl.cs
:

public class PrimaryEventHandlerImpl : IEventHandler
{
private IRsmService _rsmService;

public PrimaryEventHandlerImpl()
{

}
public PrimaryEventHandlerImpl(IRsmService rsmService)
{
_rsmService = rsmService;
}
public void MessageHandler(string json)
{
var events = JsonExtensions.JsonToObject<Event>(json);
if (events.Priority != 5)
{
//var services = _rsmService.GetServices();

}
}
}


What I want to do make it work correctly?

Answer

Change

var impl = (T)Activator.CreateInstance(queueType, parameters);

to

var impl = (T)Activator.CreateInstance(queueType, parameters.ToArray());
Comments