Error trying to resolve Service X or one of its autowired dependencies - How to get the inner exception?

I have a similar problem as described here. The difference is, that I do NOT get any exception on the client. Since the service has a void return type, nothing comes back. If I look into fiddler, I see the above error message, but I cannot see an Inner Exception anywhere.

HTTP/1.1 200 OK
Date: Fri, 27 Jul 2018 14:14:21 GMT
Server: Kestrel
Content-Length: 194

Error: Exception: Error trying to resolve Service 'BizBusDataExchangeServer.ServiceInterface.Services.DataExchangeService' or one of its autowired dependencies (see inner exception for details).

It looks like my service method is not called since no breakpoints are hit. (Which seems logic if it cannot find the implementation) But the service should be automatically added to Func since it is a ‘normal’ ServiceStack service, which should be automatically added to Func. The service itself is pretty simple:

    public void Post(ImportTopalTenants request)
    {
        Logger.Debug($"Sending a command to retrieve all tenants from topal server.");
        var databaseName = $"{BbDeConstants.SysDbName}{request.PlatformId.ToString()}";
        var queryTenantsMsg = new TenantQueryMsg
        {
            PublisherId = BbDeConstants.MyPublisherId,
            MessageId = Guid.NewGuid().ToString(),
            QueryMsg = new TenantQueryMsgDto()
        };
        var platformId = request.PlatformId;
        var rk = $"toac-{platformId.ToString()}.queries";
        MessageSender.SendMessage(queryTenantsMsg, BbMessageApiConstants.CommandExchange, rk, databaseName, GetSession().UserAuthName);
    }

The last line is a call to a static method which sends the created object to RabbitMQ. Inside this method I resolve the RabbitMQ client from the IOC:

 //....
 try
 {
       **var bus = HostContext.Resolve<IBus>().Advanced;**
       var msg = new Message<T>(message) { Properties = { ContentType = "application/json" } };
       msg.Properties.Type = msg.GetType().Name;
       var exchange = new Exchange(exchangeName);
       bus.Publish(exchange, msgRoutingKey, false, msg);
  }
 //....

And in my AppHost.cs I register the client in the AfterInitCallbacks.Add(host => ... lambda like so:

                try
                {
                    var rabbitConnectString = myConfiguration.GetRabbitMqConnectString(rabbitVHost);
                    var msgBus = RabbitHutch.CreateBus(rabbitConnectString);
                    **container.Register(msgBus);**
                }
                catch (Exception ex)
                {
                    Logger.Error(
                        $"Error connecting to RabbitMQ with connectionString {myConfiguration.GetRabbitMqConnectString(rabbitVHost)}. Error: {ex}");
                    throw;
                }

I also register queue listeners by retrieving the client from the IOC container without any error.

So how can I get more information about this inner exception??

By the way: I get this error with several calls to this service, one returns a strange exeption on the client: Type definitions should start with a '{', expecting serialized type 'MyDataType', got string with: Error:

Any idea how I can get more details about these errors?

Like I mentioned earlier, enable Debug Logger, register Exception Handlers. If you haven’t already read through the entire Error Handling page which contains information relevant to Error Handling as it describes other options like being able override OnExceptionTypeFilter() in your AppHost to customize the populated ErrorResponse.

If you’re using MQ, messages with Exceptions are published to the .dlq also the RegisterHandler APIs have a callback which you can register an Exception Handler on.

Hi Demis,
Thanks, but I know RabbitMQ quite well, I use it in many services and I wrote a C# library wrapping the REST API to manage the server (create vHosts, Users, exchanges, queues, …)

As I wrote in my original message, the call is not reaching my service at all, so there is no chance to send a message to the broker.

And yes I added errorhandling as you mentioned it in the other thread, but it does not write anything there. On the server I see the following two lines:

2018-07-29 08:14:19.733 +02:00 [INF] [Microsoft.AspNetCore.Hosting.Internal.WebHost] [ThreadId 8] Request starting HTTP/1.1 GET http://linuxdev-tbws2:6082/bbde/importqueue/topaltenants/search/95271886?dataExType=Import&dataExImportSource=TopalSoft  
2018-07-29 08:14:20.485 +02:00 [INF] [Microsoft.AspNetCore.Hosting.Internal.WebHost] [ThreadId 8] Request finished in 752.5915ms 200 

Both are from .NET core only, looks like ServiceStack code is not even touched (but I am not sure here)… The interesting thing is, it returns 200 = OK!!

On the client, I get a client exception from ServiceStack.text which fails in deserializing the answer:

2018-07-29 08:15:15.017 +02:00 [ERR] [OperationsManagerClient.ViewModels.DataExchange.DataExTenantImportTopalViewModel] [ThreadId: 1] Msg: Failed to retrieve list of imported tenants from database! Error: Type definitions should start with a ‘{’, expecting serialized type ‘DataExchangeTenantDto’, got string starting with: Error:, Exception: System.Runtime.Serialization.SerializationException: Type definitions should start with a ‘{’, expecting serialized type ‘DataExchangeTenantDto’, got string starting with: Error:
bei ServiceStack.Text.Common.DeserializeTypeRefJson.StringToType(TypeConfig typeConfig, StringSegment strType, EmptyCtorDelegate ctorFn, Dictionary2 typeAccessorMap) bei ServiceStack.Text.Common.DeserializeType1.<>c__DisplayClass2_0.b__1(StringSegment value)
bei ServiceStack.Text.Common.DeserializeListWithElements2.ParseGenericList(StringSegment value, Type createListType, ParseStringSegmentDelegate parseFn) bei ServiceStack.Text.Common.DeserializeList2.<>c__DisplayClass7_0.b__0(StringSegment value)
bei ServiceStack.Text.Json.JsonReader1.Parse(StringSegment value) bei ServiceStack.Text.Json.JsonReader1.Parse(String value)
bei ServiceStack.Text.JsonSerializer.DeserializeFromString[T](String value)
bei ServiceStack.StringExtensions.FromJson[T](String json)
bei ServiceStack.JsonHttpClient.<>c__DisplayClass118_01.<ConvertToResponse>b__3(Task1 task)
bei System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke() bei System.Threading.Tasks.Task.Execute() --- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde --- bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) bei System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
bei OperationsManagerClient.ViewModels.DataExchange.DataExTenantImportTopalViewModel.d__46.MoveNext() in D:\Projects\BizBusOpsManagerClient\OperationsManagerClient\ViewModels\DataExchange\DataExTenantImportTopalViewModel.cs:Zeile 187.

Fiddler is the only place where I can see the data sent back. It is the bit I postet at the beginning of my first post, here again:

HTTP/1.1 200 OK
Date: Sun, 29 Jul 2018 06:31:59 GMT
Server: Kestrel
Transfer-Encoding: chunked

c2
Error: Exception: Error trying to resolve Service ‘BizBusDataExchangeServer.ServiceInterface.Services.DataExchangeService’ or one of its autowired dependencies (see inner exception for details).
0

It shows 200 OK, but then there are these three last lines I do NOT understand and also who creates them, .NETcore or ServiceStack?

Error: <------ Where does this error come from?? The BizBusDataExchangeServer.ServiceInterface.Services.DataExchangeService is the service class which implements the method which is called. Is this ServiceStack or .NETcore???

The request seems to be OK, it contains the properties from the RequestDTO

GET http://linuxdev-tbws2:6082/bbde/importqueue/topaltenants/search/95271886?dataExState=AddedToImportQueue&dataExType=Import&dataExImportSource=TopalSoft HTTP/1.1
Accept: application/json
Host: linuxdev-tbws2:6082
Cookie: ss-id=6goSBTJKaIO3MRfXz5yj; ss-pid=ZfPAWzjXmGZ72nTh1tXZ
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

So it looks like ServiceStack gets a response which has an unexpected format and therefore throws the error shown above. The question is: WHY IS 200 RETURNED BUT IN FACT IT CONTAINS AN ERROR??
The assembly containing all my service implementations is referenced as a Project. So I do not see what is going wrong here…

Your Service wont be able to get called since an instance of it can’t be created.

If it doesn’t have a Powered-By ServiceStack in the Response Headers than it’s unlikely that ServiceStack is returning the response.

With that said the issue is because ServiceStack can’t create an instance of your DataExchangeService Service class. You can try resolving your Service in your AppHost Configure() to see if you can inspect the Exception thrown:

try {
using (var service = container.Resolve<DataExchangeService>()) { //should throw
}
} catch(Excetion e) { ... }

From what I’ve seen from your previous posts I’m assuming it’s due to your project dependencies being improperly configured. Basically when an instance is created from a Type from a .dll/dependency that .NET can’t find it will throw a runtime Exception. Although there’s not enough info to be able to determine that’s the cause here, but I’m guessing that continues to be the cause of your issues.

Yeah, I completely agree, but I could not found what the reason is and how to correct it.

Your suggestion seems to be correct, it throws and exception but it gets more and more confusing… Here is the result:

System.Exception: Error trying to resolve Service ‘BizBusDataExchangeServer.ServiceInterface.Services.DataExchangeService’ or one of its autowired dependencies (see inner exception for details). —> System.Exception: Error trying to resolve Service ‘System.String’ or one of its autowired dependencies (see inner exception for details). —> System.InvalidOperationException: No service for type ‘System.String’ has been registered.
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at ServiceStack.NetCore.NetCoreContainerAdapter.ResolveT
at Funq.Container.b__76_2[TService,TFunc](Container c)
at Funq.Container.ResolveImpl[TService](String name, Boolean throwIfMissing)
— End of inner exception stack trace —
at Funq.Container.ResolveImpl[TService](String name, Boolean throwIfMissing)
at Funq.Container.ResolveNamed[TService](String name)
at Funq.Container.ResolveTService
at lambda_method(Closure , Container )
at Funq.Container.ResolveImpl[TService](String name, Boolean throwIfMissing)
— End of inner exception stack trace —
at Funq.Container.ResolveImpl[TService](String name, Boolean throwIfMissing)
at Funq.Container.ResolveNamed[TService](String name)
at Funq.Container.ResolveTService
at BizBusDataExchangeServer.AppHost.Configure(Container container) in /home/tbednarz/Projects/BizBusDataExchangeServer/BizBusDataExchangeServer/AppHost.cs:line 162

It searches for a service named System.String … It is strange…

This is coming from Microsoft.Extensions.DependencyInjection and Microsoft refers to dependencies as Services.
Do you have a public string instance property on the class or a constructor with a string property or something weird you’re doing with strings?

If you want to add source code or xml to a post you should put them within triple backticks, e.g:

```xml
<!-- xml -->
```

Or C#

```csharp
// C#
```

Yeah, I wanted to post the csproj file, I have removed it…

Regarding the constructor: Yes but I just realized that this is old code!

    public DataExchangeService(string topalServerUri, string topalGrantType, string topalUserName, string topalPassword)
    {
        _mapper = AutomapperConfigManager.Instance.Mapper;
        _topalServerUri = topalServerUri;

        _loginParameters = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("grant_type", topalGrantType),
            new KeyValuePair<string, string>("username", topalUserName),
            new KeyValuePair<string, string>("password", topalPassword),
        };
    }

This comes from a stage of the software about 10 months back when I connected to a third party software using a REST api… It is replaced with RabbitMQ messaging now and I can use a parameterless constructor. I am just refactoring it…

Ok, I think I was registering this service differently at that time, but I need to look in the old version control system… it was long before I ported the stuff to .NETCore…

I now get an unauthorized error which is correct…

I have another topic regarding authentication, but I will ask separately. I think this is solved. However, resolving dependencies is still a problem since I have to add all of my own libraries in the root project, .NETCore seems not to be able to resolve them recursively…

Maybe I should create kind of a ‘private NuGet repository’ to store all my stuff which I need everywhere. Don’t know if this is efficient but probably better then copy DLLs around all the time…