Autofac: Autofac.Core.DependencyResolutionException - c#

The server runs but when I try to connect to the server I recieve this Exception:
2023-01-12 15:10:00,023 [12] ERROR Photon.SocketServer.Peers.ManagedPeer - Autofac.Core.DependencyResolutionException:
An exception was thrown while activating NinjaBricks.NinjaPhoton.Implementation.Client.PhotonClientPeer ->
NinjaBricks.Framework.Implementation.Messaging.ClientHandlerList ->
λ:NinjaBricks.Framework.Interfaces.Messaging.IHandler`1[[NinjaBricks.Framework.Interfaces.Client.IClientPeer, NinjaBricks.Framework,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]][] -> NinjaBricks.NinjaPhoton.Implementation.Handler.ClientRequestForwardHandler.
---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'NinjaBricks.NinjaPhoton.Implementation.Handler.ClientRequestForwardHandler' can be invoked with the available services and parameters:
Cannot resolve parameter 'NinjaBricks.Framework.Interfaces.Support.IClientCodeRemover clientCodeRemover' of constructor
'Void .ctor(ExitGames.Logging.ILogger,
NinjaBricks.Framework.Interfaces.Server.IServerConnectionCollection`2
[NinjaBricks.Framework.Interfaces.Config.IServerType,
NinjaBricks.Framework.Interfaces.Server.IServerPeer],
NinjaBricks.Framework.Interfaces.Support.IClientCodeRemover,
NinjaBricks.Framework.Interfaces.Config.IServerType)'.
en Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(ConstructorInfo[] availableConstructors, IComponentContext context, IEnumerable`1 parameters)
en Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
en Autofac.Core.Resolving.InstanceLookup.CreateInstance(IEnumerable`1 parameters)
--- Fin del seguimiento de la pila de la excepción interna ---
en Autofac.Core.Resolving.InstanceLookup.CreateInstance(IEnumerable`1 parameters)
en Autofac.Core.Resolving.InstanceLookup.Execute()
en Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request)
en Autofac.Core.Resolving.ResolveOperation.Execute(ResolveRequest request)
en lambda_method(Closure , InitRequest )
en NinjaBricks.NinjaPhoton.Implementation.PhotonPeerFactory.CreatePeer[T](IPeerConfig config) en D:\Users\pndia\Documents\GitHub\NinjaBricks\ninja-bricks-game-server\NinjaBricks.NinjaPhoton\Implementation\PhotonPeerFactory.cs:línea 61
en Photon.SocketServer.Peers.ManagedPeer.CreatePeerBase(InitRequest initRequest)
The code was made by other programmer and It is old code, but I Can't run it properly and i have no documentation about the code.
This is the ClientRequestForwardHandler class:
using ExitGames.Logging;
using NinjaBricks.Common;
using NinjaBricks.Common.Codes;
using NinjaBricks.Framework.Implementation.Config;
using NinjaBricks.Framework.Implementation.Messaging;
using NinjaBricks.Framework.Interfaces.Client;
using NinjaBricks.Framework.Interfaces.Config;
using NinjaBricks.Framework.Interfaces.Messaging;
using NinjaBricks.Framework.Interfaces.Server;
using NinjaBricks.Framework.Interfaces.Support;
using System;
using System.Linq;
namespace NinjaBricks.NinjaPhoton.Implementation.Handler
{
public class ClientRequestForwardHandler : IHandler<IClientPeer>, IDefaultRequestHandler<IClientPeer>
{
private readonly IServerConnectionCollection<IServerType, IServerPeer> _serverConnectionCollection;
private readonly IClientCodeRemover _clientCodeRemover;
private readonly IServerType _serverType;
public ILogger Log { get; set; }
public byte Code { get => 0x0ff; }
public int? SubCode { get => null; }
public MessageType Type { get => MessageType.Request; }
public ClientRequestForwardHandler(ILogger log,
IServerConnectionCollection<IServerType, IServerPeer> serverConnectionCollection,
IClientCodeRemover clientCodeRemover,
IServerType serverType)
{
Log = log;
_serverConnectionCollection = serverConnectionCollection;
_clientCodeRemover = clientCodeRemover;
_serverType = serverType;
}
public bool HandleMessage(IMessage message, IClientPeer clientPeer)
{
if (!message.Parameters.ContainsKey((byte)ParameterCode.ServerType))
{
return false;
}
var serverType = _serverType.GetServerType(Convert.ToInt32(message.Parameters[(byte)ParameterCode.ServerType]));
var server = _serverConnectionCollection.GetServersByType<IServerPeer>(serverType).FirstOrDefault();
if (server != null)
{
_clientCodeRemover.RemoveServerType(message);
_clientCodeRemover.RemovePeerId(message);
AddMessageCodes(message, clientPeer);
server.SendMessage(message);
return true;
}
return false;
}
private void AddMessageCodes(IMessage message, IClientPeer clientPeer)
{
message.Parameters.Add((byte)ParameterCode.PeerId, clientPeer.PeerId.ToByteArray());
}
}
}
And this is the IClientCodeRemover:
using NinjaBricks.Common.Codes;
using NinjaBricks.Framework.Interfaces.Messaging;
using NinjaBricks.Framework.Interfaces.Support;
namespace NinjaBricks.Framework.Implementation.Support
{
public class ClientCodeRemover : IClientCodeRemover
{
public void RemovePeerId(IMessage message)
{
message.Parameters.Remove((byte)MessageParameterCode.PeerId);
}
public void RemoveServerType(IMessage message)
{
message.Parameters.Remove((byte)ParameterCode.ServerType);
}
public void RemoveName(IMessage message)
{
message.Parameters.Remove((byte)ParameterCode.Name);
}
}
}
Also here the configs of autofac:
using Autofac;
using NinjaBricks.NinjaPhoton.Implementation;
using NinjaBricks.NinjaPhoton.Implementation.Client;
using NinjaBricks.NinjaPhoton.Implementation.Data;
using NinjaBricks.NinjaPhoton.Implementation.Handler;
using NinjaBricks.NinjaPhoton.Implementation.Server;
using NinjaBricks.Framework.Implementation.Client;
using NinjaBricks.Framework.Implementation.Config;
using NinjaBricks.Framework.Implementation.Messaging;
using NinjaBricks.Framework.Implementation.Server;
namespace NinjaBricks.NinjaPhoton.Modules
{
public class ProxyServerModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<ServerApplication>().AsImplementedInterfaces().SingleInstance();
builder.RegisterType<PhotonPeerFactory>().AsImplementedInterfaces().SingleInstance();
builder.RegisterType<PeerConfig>().AsImplementedInterfaces();
builder.RegisterType<SubServerClientPeer>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<PhotonClientPeer>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<PhotonServerPeer>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<ServerConnectionCollection>().AsImplementedInterfaces().SingleInstance();
builder.RegisterType<ClientConnectionCollection>().AsImplementedInterfaces().SingleInstance();
builder.RegisterType<ServerHandlerList>().AsImplementedInterfaces();
builder.RegisterType<EventForwardHandler>().AsImplementedInterfaces();
builder.RegisterType<RequestForwardHandler>().AsImplementedInterfaces();
builder.RegisterType<ResponseForwardHandler>().AsImplementedInterfaces();
builder.RegisterType<ClientHandlerList>().AsImplementedInterfaces();
builder.RegisterType<ClientRequestForwardHandler>().AsImplementedInterfaces();
builder.RegisterType<ServerRegistrationHandler>().AsImplementedInterfaces();
builder.RegisterType<ServerData>().AsImplementedInterfaces();
}
}
}
Autofac version 5.2.0

Based on the provided code it seems that you have forgot to register ClientCodeRemover. Try adding:
builder.RegisterType<ClientCodeRemover>().AsImplementedInterfaces();
To your ProxyServerModule.Load method.

Related

Autofac.Core.DependencyResolutionException: An exception was thrown while activating Blazor.Pages.Shared.CustomerGrid -> CustomerAppService

I implemented DDD using ABP framework, but I don't know which part is wrong. It's a simple project that follows the ABP tutorial.
use : .net6 telerik blazor mssql
Error: Autofac.Core.DependencyResolutionException: An exception was thrown while activating A.Blazor.Pages.Shared.CustomerGrid -\> A.Customers.CustomerAppService.
\---\> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'A.Customers.CustomerAppService' can be invoked with the available services and parameters:
Cannot resolve parameter 'A.Customers.ICustomerRepository customerRepository' of constructor 'Void .ctor(A.Customers.ICustomerRepository)'.
at Autofac.Core.Activators.Reflection.ReflectionActivator.\<\>c__DisplayClass12_0.\<UseSingleConstructorActivation\>b__0(ResolveRequestContext ctxt, Action`1 next) at Autofac.Core.Resolving.Middleware.DisposalTrackingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
at Autofac.Builder.RegistrationBuilder`3.<>c__DisplayClass41_0.<PropertiesAutowired>b__0(ResolveRequestContext ctxt, Action`1 next)
at Autofac.Extras.DynamicProxy.RegistrationExtensions.\<\>c__DisplayClass8_0`3.<EnableInterfaceInterceptors>b__1(ResolveRequestContext ctxt, Action`1 next)
at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action`1 next) --- End of inner exception stack trace --- at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
at Autofac.Core.Resolving.Middleware.SharingMiddleware.Execute(ResolveRequestContext context, Action`1 next) at Autofac.Core.Resolving.Middleware.CircularDependencyDetectorMiddleware.Execute(ResolveRequestContext context, Action`1 next)
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request)
at Autofac.Core.Resolving.ResolveOperation.ExecuteOperation(ResolveRequest request)
at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters)
at Blazorise.ComponentActivator.CreateInstance(Type componentType)
at Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(IServiceProvider serviceProvider, Type componentType)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.InstantiateChildComponentOnFrame(RenderTreeFrame& frame, Int32 parentComponentId)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(DiffContext& diffContext, Int32 frameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(DiffContext& diffContext, Int32 frameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(DiffContext& diffContext, Int32 newFrameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(DiffContext& diffContext, Int32 newFrameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(DiffContext& diffContext, Int32 newFrameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(DiffContext& diffContext, Int32 oldStartIndex, Int32 oldEndIndexExcl, Int32 newStartIndex, Int32 newEndIndexExcl)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, Int32 componentId, ArrayRange`1 oldTree, ArrayRange`1 newTree)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
[Blazor]
Paged.Shared > CustomerComboBox.raozr
#using A.Customers
<Telerik.Blazor.Components.TelerikComboBox
TItem="#CustomerDto"
TValue="int"
OnRead="#GetCustomer"
Placeholder="Select Customer"
ClearButton="true"
TextField="#nameof(CustomerDto.name)"
ValueField = "#nameof(CustomerDto.customer_id)"
Value="#selectCustomer"
></Telerik.Blazor.Components.TelerikComboBox>
Paged.Shared > CustomerComboBox.razor.cs
using A.Customers;
using System.Threading.Tasks;
using Telerik.Blazor.Components;
namespace A.Blazor.Pages.Shared
{
public partial class CustomerCombo
{
private readonly ICustomerAppService _customerAppService;
public int selectCustomer { get; set; }=0;
public CustomerCombo(ICustomerAppService customerAppService)
{
_customerAppService = customerAppService;
}
public async Task GetCustomer(ComboBoxReadEventArgs args)
{
args.Data = await _customerAppService.GetCustomerAppService();
}
}
}
[Application.Contracts]
Customers > CustomerDto.cs
namespace A.Customers
{
public class CustomerDto
{
public int customer_id { get; set; }
public string name { get; set; }
}
}
Customers > ICustomerAppService.cs
namespace A.Customers
{
public interface ICustomerAppService : IApplicationService
{
Task<List<CustomerDto>> GetCustomerAppService();
}
}
[Application]
Customers > CustomerAppService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace A.Customers
{
public class CustomerAppService : AAppService, ICustomerAppService
{
private readonly ICustomerRepository _customerRepository;
public CustomerAppService(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
public async Task<List<CustomerDto>> GetCustomerAppService()
{
var customers = await _customerRepository.GetListCustomerAsync();
return ObjectMapper.Map<List<Customer>, List<CustomerDto>>(customers);
}
}
}
AAppService.cs
using ATAG.Localization;
using Volo.Abp.Application.Services;
namespace A;
public abstract class AAppService : ApplicationService
{
protected AAppService()
{
LocalizationResource = typeof(AResource);
}
}
AApplicationAutiMapperProfile.cs
using AutoMapper;
using ATAG.Customers;
namespace A;
public class AApplicationAutoMapperProfile : Profile
{
public AApplicationAutoMapperProfile()
{
CreateMap<Customer, CustomerDto>();
CreateMap<CustomerDto, Customer>();
}
}
[Domain]
Customers > Customer.cs
namespace A.Customers
{
public class Customer
{
public int customer_id { get; set; }
public string name { get; set; }
}
}
Customers > ICustomerRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace A.Customers
{
public interface ICustomerRepository
{
Task<List<Customer>> GetListCustomerAsync();
}
}
[EFCore]
Customers > CustomerRepository.cs
using Dapper;
using A.EntityFrameworkCore;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.Dapper;
using Volo.Abp.EntityFrameworkCore;
namespace A.Customers
{
public class CustomerRepository : DapperRepository<ADbContext>, ICustomerRepository
{
public CustomerRepository(IDbContextProvider<ADbContext> dbContextProvider) : base(dbContextProvider)
{
}
public async Task<List<Customer>> GetListCustomerAsync()
{
var dbConnection = await GetDbConnectionAsync();
StringBuilder builder = new StringBuilder();
builder.AppendFormat(#"
SELECT cust_id, name
FROM T_CUSTOMER );
var customers = await dbConnection.QueryAsync<Customer>(
builder.ToString(),
null,
transaction: await GetDbTransactionAsync(),
commandType: CommandType.Text
);
List<Customer> emptyList = new List<Customer>();
return (List<Customer>)customers;
}
}
}
AEntityFrameworkCoreModule
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddAbpDbContext<ADbContext>(options =>
{
/* Remove "includeAllEntities: true" to create
* default repositories only for aggregate roots */
options.AddDefaultRepositories(includeAllEntities: true);
});
}
The "ICustomerRepository" interface should inherit from "IDapperRepository" similar to how your CustomerRepository class does and the names of the fields you use in your database should have the same name:
In your database you have these fields
cust_id, name
In your class you have these,
customer_id, name
They should have the same name so that dapper can map them or you can create an alias in your query.

A second operation started

When I start my page everything loads fine I try to reload for the second time I get the following error
I run the urls from angular
A second operation started on this context before a previous
asynchronous operation completed. Use 'await' to ensure that any
asynchronous operations have completed before calling another method
on this context. Any instance members are not guaranteed to be thread
safe.
This is the method
private readonly PuntovService puntovService = new PuntovService(new PuntovRepository(CentralContext.Create()));
private readonly IMapper mapper;
public PuntovController()
{
this.mapper = WebApiApplication.MapperConfiguration.CreateMapper();
}
[HttpGet]
[Route("Puntos")]
[ResponseType(typeof(IEnumerable<PuntovDTO>))]
public async Task<IHttpActionResult> GetAll()
{
var pv = await puntovService.GetAll();
var puntovDTO = pv.Select(x => mapper.Map<PuntovDTO>(x));
var tipoComitePersona = from com in puntovDTO
select new {com.PuntoV};
return Ok(tipoComitePersona);
}
in this class call the context that would be the database
using APICentralBL.Models;
using System.Data.Entity;
namespace APICentralBL.Data
{
public class CentralContext : DbContext
{
private static CentralContext centralContext = null;
public CentralContext() : base("Context")
{
}
public DbSet<SDN> SDN { get; set;}
public DbSet<CALIF> CALIF { get; set; }
public DbSet<UVT> UVT { get; set; }
public DbSet<PUNTOV> PUNTOV { get; set; }
public DbSet<TRANS> TRANS { get; set; }
public static CentralContext Create()
{
if (centralContext == null)
centralContext = new CentralContext();
return centralContext;
}
}
}
It not only happens with this method, it happens when I try to call more than one
ex.StackTrace
en System.Data.Entity.Internal.ThrowingMonitor.EnsureNotEntered()
en System.Data.Entity.Core.Objects.ObjectQuery`1.System.Data.Entity.Infrastructure.IDbAsyncEnumerable<T>.GetAsyncEnumerator()
en System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ForEachAsync[T](IDbAsyncEnumerable`1 source, Action`1 action, CancellationToken cancellationToken)
en System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ToListAsync[T](IDbAsyncEnumerable`1 source, CancellationToken cancellationToken)
en System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ToListAsync[T](IDbAsyncEnumerable`1 source)
en APICentralBL.Repositories.Implements.GenericRepository`1.<GetAll>d__3.MoveNext() en D:\ANTIOQUENA DEVELOPERS REPOSITORY\ANTIOQUENA DEVELOPERS\DEVELOPMENTS\API'S PROJECT\APICentral-Deploy\APICentralBL\Repositories\Implements\GenericRepository.cs: línea 33
en System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
en System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
en APICentralBL.Services.Implements.GenericService`1.<GetAll>d__3.MoveNext() en D:\ANTIOQUENA DEVELOPERS REPOSITORY\ANTIOQUENA DEVELOPERS\DEVELOPMENTS\API'S PROJECT\APICentral-Deploy\APICentralBL\Services\Implements\GenericService.cs: línea 25
en System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
en System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
en APICentral.Controllers.PuntovController.<GetAll>d__4.MoveNext() en D:\ANTIOQUENA DEVELOPERS REPOSITORY\ANTIOQUENA DEVELOPERS\DEVELOPMENTS\API'S PROJECT\APICentral-Deploy\APICentral\Controllers\PuntovController.cs: línea 65**
Since your context is stored in a static field, it will be shared by all threads serving requests to your controllers concurrently. You should usually use a context per request

Signalr Sending messages from server to client c# An unhandled exception has occurred while executing the request

My error:
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'AgencyApi.Controllers.LicenseInfoController'. There should only be one applicable constructor.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.TryFindMatchingConstructor(Type instanceType, Type[] argumentTypes, ConstructorInfo& matchingConstructor, Nullable`1[]& parameterMap)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, ConstructorInfo& matchingConstructor, Nullable`1[]& parameterMap)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateFactory(Type instanceType, Type[] argumentTypes)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.CreateActivator(ControllerActionDescriptor descriptor)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.CreateControllerFactory(ControllerActionDescriptor descriptor)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvokerCache.GetCachedResult(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvokerProvider.OnProvidersExecuting(ActionInvokerProviderContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionInvokerFactory.CreateInvoker(ActionContext actionContext)
at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointFactory.<>c__DisplayClass7_0.<CreateRequestDelegate>b__0(HttpContext context)"
My SignalRhub.cs
using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;
namespace AgencyApi
{
public class SignalRHub:Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
My LicenseInfoController.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using AgencyApi.Data.Entities;
using Microsoft.AspNetCore.Mvc;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Microsoft.AspNetCore.SignalR;
using AgencyApi;
namespace AgencyApi.Controllers
{
[Route("api/[controller]")]
public class LicenseInfoController : BaseController
{
private readonly ILicenseInfoService _licenseService;
[HttpPost("ConfirmLink")]
public async Task<JObject> ConfirmLink(LicenseInfo value)
{
JObject res = new JObject();
try
{
var menuService = (IMenuService)this.HttpContext.RequestServices.GetService(typeof(IMenuService));
var model = await _licenseService.GetById(value.id);
model.Status = value.Status;
model.Reason = value.Reason;
var result = await _licenseService.Update(model);
res.Add("ok", true);
res.Add("data", JObject.FromObject(result));
}
catch (Exception ex)
{
res.Add("error", ex.Message);
}
SendToAll();
return res;
}
private readonly IHubContext<SignalRHub> _hubContext;
public LicenseInfoController(IHubContext<SignalRHub> hubContext)
{
_hubContext = hubContext;
}
public void SendToAll()
{
_hubContext.Clients.All.SendAsync("Send", "message");
}
}
}
I think you are copying some bad example. I would suggest a different approach
Make you SignalRinterface as a service, not a derivative:
public class SignalRHub
{
public Task SendMessage(string user, string message) =>
_hubContext.Clients.All.SendAsync("ReceiveMessage", user, message);
public Task SendToAll(string message) =>
_hubContext.Clients.All.SendAsync("Send", message);
private readonly IHubContext<Hub> _hubContext;
public SignalRHub(IHubContext<Hub> hubContext) =>
_hubContext = hubContext;
}
Register in Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSignalR();
services.AddSingleton<SignalRHub>();
}
Then add to the controller:
public class LicenseInfoController : Controller
{
[HttpPost]
public async Task<JObject> ConfirmLink(string value)
{
JObject res = new JObject();
await _signalRHub.SendToAll("message");
return res;
}
private readonly SignalRHub _signalRHub;
public LicenseInfoController(SignalRHub signalRHub)
{
_signalRHub = signalRHub;
}
}

'unitOfWork parameter cannot be null' in Background Worker

I've started getting these errors. It was working perfectly on my previous server.
using System;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Threading.BackgroundWorkers;
using EMS.IPs;
using System.Threading.Tasks.Dataflow;
using System.Threading.Tasks;
using System.Linq;
using EMS.Contacts;
using System.Collections.Concurrent;
using Abp.Domain.Uow;
using System.Collections.Generic;
using EMS.EmailValidation;
using Microsoft.AspNetCore.SignalR;
using KellermanSoftware.NetEmailValidation;
using System.Net;
using System.Collections;
using System.Threading;
using System.ComponentModel;
using System.Transactions;
namespace EMS.BackgroundWorkers
{
public class ContactValidationBackgroundWorker : BackgroundWorkerBase, ITransientDependency
{
private readonly IRepository<IP> _ipsRepository;
private readonly IRepository<Contact> _contactsRepository;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly IUnitOfWorkManager _unitOfWorkManager2;
private readonly IRepository<Contact> _contactRepository;
private BackgroundWorker bgworker = new BackgroundWorker();
ActionBlock<ValidationObject> workerBlock;
public ContactValidationBackgroundWorker(
IRepository<IP> ipsRepository,
IRepository<Contact> contactsRepository,
IUnitOfWorkManager unitOfWorkManager,
IUnitOfWorkManager unitOfWorkManager2,
IRepository<Contact> contactRepository)
{
_ipsRepository = ipsRepository;
_contactsRepository = contactsRepository;
_unitOfWorkManager = unitOfWorkManager;
_unitOfWorkManager2 = unitOfWorkManager2;
_contactRepository = contactRepository;
bgworker.DoWork += Worker;
}
public override void Start()
{
base.Start();
bgworker.RunWorkerAsync();
}
public override void Stop()
{
bgworker.DoWork -= Worker;
}
public void Worker(object sender, DoWorkEventArgs e)
{
using (var unitOfWork = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
{
var contacts = _contactsRepository.GetAll().Where(x => !x.IsChecked);
if (!contacts.Any())
{
Logger.Debug("No contacts");
return;
}
workerBlock = new ActionBlock<ValidationObject>(
async (arg) => await Validate(arg),
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 5
});
foreach (var contact in contacts)
{
workerBlock.Post(new ValidationObject()
{
Contact = contact
});
}
unitOfWork.Complete();
}
Logger.Debug("End posting jobs to threads. Awaits results...");
workerBlock.Complete();
workerBlock.Completion.Wait();
}
public override void WaitToStop()
{
base.WaitToStop();
}
private async Task Validate(ValidationObject validationObject)
{
try
{
using (var contactUnitOfWork = _unitOfWorkManager2.Begin(TransactionScopeOption.RequiresNew))
{
Contact contact = validationObject.Contact;
contact.IsChecked = true;
await _contactRepository.UpdateAsync(contact);
await contactUnitOfWork.CompleteAsync();
}
} catch (Exception ex) {
Logger.Error(ex.ToString());
throw;
}
}
}
public class ValidationResult
{
public ValidationResult()
{
IsValid = false;
Message = "";
}
public string Message { get; set; }
public bool IsValid { get; set; }
}
public class ValidationObject
{
public Contact Contact { get; set; }
}
}
It works inside background worker; it worked before. Now it doesn't. Contact object is not null.
It seems to ask me to add unitOfWork parameter to Update method. Please help me figure this out.
ERROR 2017-12-26 12:02:34,768 [14 ] orkers.ContactValidationBackgroundWorker - System.ArgumentNullException: Value cannot be null.
Parameter name: unitOfWork
at Abp.EntityFrameworkCore.Uow.UnitOfWorkExtensions.GetDbContext[TDbContext](IActiveUnitOfWork unitOfWork, Nullable`1 multiTenancySide)
at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.Update(TEntity entity)
at Castle.Proxies.Invocations.IRepository`2_Update_8.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Abp.Domain.Uow.UnitOfWorkInterceptor.PerformSyncUow(IInvocation invocation, UnitOfWorkOptions options)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IRepository`1Proxy_3.Update(Contact entity)
at EMS.BackgroundWorkers.ContactValidationBackgroundWorker.<Validate>d__21.MoveNext() in /Users/grinay/Projects/EMSBackend/src/EMS.Application/BackgroundWorkers/ContactValidationBackgroundWorker.cs:line 329
UPDATE1
ERROR 2017-12-27 05:31:34,500 [9 ] orkers.ContactValidationBackgroundWorker - System.ArgumentNullException: Value cannot be null.
Parameter name: unitOfWork
at Abp.EntityFrameworkCore.Uow.UnitOfWorkExtensions.GetDbContext[TDbContext](IActiveUnitOfWork unitOfWork, Nullable`1 multiTenancySide)
at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.UpdateAsync(TEntity entity)
at Castle.Proxies.Invocations.IRepository`2_UpdateAsync_8.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Abp.Domain.Uow.UnitOfWorkInterceptor.PerformAsyncUow(IInvocation invocation, UnitOfWorkOptions options)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IRepository`1Proxy_3.UpdateAsync(Contact entity)
at EMS.BackgroundWorkers.ContactValidationBackgroundWorker.<>c__DisplayClass23_0.<<Validate>b__0>d.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 Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- 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 Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at Nito.AsyncEx.AsyncContext.Run(Func`1 action)
at EMS.BackgroundWorkers.ContactValidationBackgroundWorker.Validate(ValidationObject validationObject)
You cannot use async methods with unitOfWork like that in background worker.
Make the changes in these 5 lines:
public void Worker(object sender, DoWorkEventArgs e)
{
// ...
workerBlock = new ActionBlock<ValidationObject>(
(arg) => Validate(arg), // This line #1
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 5
});
// ...
}
private void Validate(ValidationObject validationObject) // This line #2
{
try
{
using (var contactUnitOfWork = _unitOfWorkManager2.Begin(TransactionScopeOption.RequiresNew))
{
Contact contact = validationObject.Contact;
contact.IsChecked = true;
AsyncHelper.RunSync(async () => // This line #3
{ // This line #4
await _contactRepository.UpdateAsync(contact);
await contactUnitOfWork.CompleteAsync();
}); // This line #5
}
} catch (Exception ex) {
Logger.Error(ex.ToString());
throw;
}
}

Autofac logging module & Resolved Parameter in ASP.Net Web Forms

I'm trying to use an Autofac module to inject NLog logger to asp.net Web Forms application (code behind) but i'm getting an error when trying to use a ResolvedParameter:
Global asax & Logging module:
public class Global : HttpApplication, IContainerProviderAccessor
{
static IContainerProvider _containerProvider;
public IContainerProvider ContainerProvider
{
get { return _containerProvider; }
}
void Application_Start(object sender, EventArgs e)
{
var builder = new ContainerBuilder();
builder.RegisterModule<LoggingModule>();
_containerProvider = new ContainerProvider(builder.Build());
}
}
public class LoggingModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(RegsiterFunc).AsImplementedInterfaces();
}
private NLogger RegsiterFunc(IComponentContext arg, IEnumerable<Parameter> parameters)
{
return new NLogger(parameters.TypedAs<Type>());
}
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
{
registration.Preparing +=
(sender, args) =>
{
var forType = args.Component.Activator.LimitType;
var logParameter = new ResolvedParameter(
(p, c) => p.ParameterType == typeof(ILogger),
(p, c) => c.Resolve<ILogger>(TypedParameter.From(forType)));
args.Parameters = args.Parameters.Union(new[] { logParameter });
};
}
}
NLogger class:
public class NLogger : ILogger
{
private readonly Logger m_Logger;
public NLogger(Type type)
{
m_Logger = LogManager.GetLogger(type.FullName);
}
public NLogger(string typeName)
{
m_Logger = LogManager.GetLogger(typeName);
}
.......
}
Aspx page code behind:
public partial class _Default : Page
{
public ILogger m_Logger { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
m_Logger.Error("test");
}
}
To initiate the log based on the requesting type I'm using a ResolvedParameter.
The line parameters.TypedAs() in RegsiterFunc throws an exception: "Sequence contains no elements".
Same code works in asp.net MVC application but fails in the web forms project.
System.InvalidOperationException occurred HResult=0x80131509
Message=Sequence contains no elements Source=Autofac
StackTrace: at Autofac.ParameterExtensions.ConstantValue[TParameter,TValue](IEnumerable`1 parameters, Func`2 predicate)
at Autofac.ParameterExtensions.TypedAs[T](IEnumerable`1 parameters)
at WebApplication1.LoggingModule.RegsiterFunc(IComponentContext arg, IEnumerable`1 parameters) in Global.asax.cs:line 55
at Autofac.Builder.RegistrationBuilder.<>c__DisplayClass0_0`1.b__0(IComponentContext c, IEnumerable`1 p)
at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
As far as I understand, in RegsiterFunc you are attempting to retrieve type of component the logger is being injected into.
But the parameter that carries component type is not a TypedParameter, but rather it's a NamedParameter. That's why you get the exception.
Though less elegant, but working version of RegsiterFunc:
private NLogger RegsiterFunc(IComponentContext arg, IEnumerable<Parameter> parameters)
{
var type = (Type)((NamedParameter)parameters.First()).Value;
return new NLogger(type);
}
Then for Default.aspx page, the type passed to NLogger will be ASP.default_aspx.
The second parameter you create:
new ResolvedParameter(
(p, c) => p.ParameterType == typeof(ILogger),
(p, c) => c.Resolve<ILogger>(TypedParameter.From(forType)));
is not in use, so that overriding AttachToComponentRegistration is unnecessary.

Categories

Resources