Error System.TypeInitializationException: ‘The type initializer for ‘MongoDB.Driver.Core.Misc.DnsClientWrapper’ threw an exception.’

Hi, I am finding an error whenever I try to instantiate a MongoClient or a MongoClientSettings object (from MongoDB.Driver) when passing the connection string to their constructor.

The whole error message that I can get a hold off says:

{System.TypeInitializationException: The type initializer for ‘MongoDB.Driver.Core.Misc.DnsClientWrapper’ threw an exception. —> System.AggregateException: Error resolving name servers (Object reference not set to an instance of an object.) (Could not find file “/etc/resolv.conf”) —> System.NullReferenceException: Object reference not set to an instance of an object. at DnsClient.NameServer.QueryNetworkInterfaces () [0x0004c] in <519bb9af32234e5dba6bd0b076a88151>:0 at DnsClient.NameServer.ResolveNameServers (System.Boolean skipIPv6SiteLocal, System.Boolean fallbackToGooglePublicDns) [0x0005e] in <519bb9af32234e5dba6bd0b076a88151>:0 — End of inner exception stack trace — at DnsClient.NameServer.ResolveNameServers (System.Boolean skipIPv6SiteLocal, System.Boolean fallbackToGooglePublicDns) [0x00192] in <519bb9af32234e5dba6bd0b076a88151>:0 at DnsClient.LookupClient…ctor (DnsClient.LookupClientOptions options, DnsClient.DnsMessageHandler udpHandler, DnsClient.DnsMessageHandler tcpHandler) [0x000bc] in <519bb9af32234e5dba6bd0b076a88151>:0 at DnsClient.LookupClient…ctor (DnsClient.LookupClientOptions options) [0x00000] in <519bb9af32234e5dba6bd0b076a88151>:0 at DnsClient.LookupClient…ctor () [0x00006] in <519bb9af32234e5dba6bd0b076a88151>:0 at MongoDB.Driver.Core.Misc.DnsClientWrapper…ctor () [0x00006] in :0 at MongoDB.Driver.Core.Misc.DnsClientWrapper…cctor () [0x00000] in :0 — End of inner exception stack trace — at MongoDB.Driver.Core.Configuration.ConnectionString…ctor (System.String connectionString) [0x00000] in :0 at MongoDB.Driver.MongoUrlBuilder.Parse (System.String url) [0x00000] in <27273b0202ea4c34867b683ed7b21818>:0 at MongoDB.Driver.MongoUrlBuilder…ctor (System.String url) [0x00006] in <27273b0202ea4c34867b683ed7b21818>:0 at MongoDB.Driver.MongoUrl…ctor (System.String url) [0x00000] in <27273b0202ea4c34867b683ed7b21818>:0 at MongoDB.Driver.MongoClientSettings.FromConnectionString (System.String connectionString) [0x00000] in <27273b0202ea4c34867b683ed7b21818>:0 at --REDACTED FILENAME–

The lines of code that cause this error are:

string connString = "mongodb+srv://" + user + ":" + secret + "@" + server + "/"+ project +"?retryWrites=true&w=majority";

var settings = MongoClientSettings.FromConnectionString(connString);
settings.ServerApi = new ServerApi(ServerApiVersion.V1);
var mongoClient = new MongoClient(settings);

It will break at MongoClientSettings.FromConnectionString(connString);
Or this will also break:

string connString = "mongodb+srv://" + user + ":" + secret + "@" + server + "/"+ project +"?retryWrites=true&w=majority";
var mongoClient = new MongoClient(connString);

This issue is only happening when I run this code in a Xamarin project. I have the exact same code in a .NET 6 project and everything works fine there. The Xamarin project on the other hand targets .NET Standard 2.0 (also tried 2.1 with same issue) and I’ve been debugging it in an Android 12 device. The driver versions I’ve tested are 2.4.4 and 2.18.0. IDE is Visual Studio Version 17.2.0

I appreciate any help I could get here. Thank you.

Hi @Santiago_Suarez, as this appears to be environmental (Xamarin/Android) I’d recommend opening a new ticket at https://jira.mongodb.org/projects/CSHARP/ so the Driver team can investigate this as a potential bug.

You may want to format errors as code blocks as it will improve readability.

I am not expert over android and just wandering around. could that be the problem? and if may I ask: why don’t you use string extrapolation to form your connection url?

{System.TypeInitializationException: The type initializer for ‘MongoDB.Driver.Core.Misc.DnsClientWrapper’ threw an exception. —> 
  System.AggregateException: Error resolving name servers (Object reference not set to an instance of an object.) (Could not find file “/etc/resolv.conf”) —> 
  System.NullReferenceException: Object reference not set to an instance of an object. 
    at DnsClient.NameServer.QueryNetworkInterfaces () [0x0004c] 
    in <519bb9af32234e5dba6bd0b076a88151>:0 
    at DnsClient.NameServer.ResolveNameServers (System.Boolean skipIPv6SiteLocal, System.Boolean fallbackToGooglePublicDns) [0x0005e] 
    in <519bb9af32234e5dba6bd0b076a88151>:0 
— 
End of inner exception stack trace 
— 
    at DnsClient.NameServer.ResolveNameServers (System.Boolean skipIPv6SiteLocal, System.Boolean fallbackToGooglePublicDns) [0x00192] 
    in <519bb9af32234e5dba6bd0b076a88151>:0 at DnsClient.LookupClient…ctor (DnsClient.LookupClientOptions options, DnsClient.DnsMessageHandler udpHandler, DnsClient.DnsMessageHandler tcpHandler) [0x000bc] 
    in <519bb9af32234e5dba6bd0b076a88151>:0 at DnsClient.LookupClient…ctor (DnsClient.LookupClientOptions options) [0x00000] 
    in <519bb9af32234e5dba6bd0b076a88151>:0 at DnsClient.LookupClient…ctor () [0x00006] 
    in <519bb9af32234e5dba6bd0b076a88151>:0 at MongoDB.Driver.Core.Misc.DnsClientWrapper…ctor () [0x00006] in :0 
    at MongoDB.Driver.Core.Misc.DnsClientWrapper…cctor () [0x00000] in :0 — End of inner exception stack trace — at MongoDB.Driver.Core.Configuration.ConnectionString…ctor (System.String connectionString) [0x00000] in :0 
    at MongoDB.Driver.MongoUrlBuilder.Parse (System.String url) [0x00000] 
    in <27273b0202ea4c34867b683ed7b21818>:0 at MongoDB.Driver.MongoUrlBuilder…ctor (System.String url) [0x00006] in <27273b0202ea4c34867b683ed7b21818>:0 
    at MongoDB.Driver.MongoUrl…ctor (System.String url) [0x00000] in <27273b0202ea4c34867b683ed7b21818>:0 
    at MongoDB.Driver.MongoClientSettings.FromConnectionString (System.String connectionString) [0x00000] in <27273b0202ea4c34867b683ed7b21818>:0
    at --REDACTED FILENAME–

Thank you, I’ve opened this ticket and hopefully someone will take up on it.
https://jira.mongodb.org/browse/CSHARP-4436

Thank you for the suggestion, I didn’t know how it would end up looking. Shame I can’t edit the top entry to make it more readable.

Regarding the “/etc/resolv.conf” I have no idea since that error comes from some MongoDriver component I don’t have access to, nor can I control. I don’t create nor need that file myself, but it is most likely at least very close to the issue underneath.

As for the string interpolation, that was just a fast and dirty example, but I’m pretty sure the connString variable works since the same code works in dotnet 6.

1 Like

Hi, @Santiago_Suarez,

The .NET/C# Driver uses DnsClient.NET, a third-party DNS library, for resolving SRV and TXT records. Unfortunately it appears that increased security restrictions around DNS introduced in Android Oreo prevent DnsClient.NET from working correctly. See issue #17 in DnsClient.NET’s issue tracker. Given that the issue is closed, it doesn’t appear that a fix is forthcoming.

You can work around this issue by using the standard connection string format (AKA mongodb://) rather than the DNS seedlist format (AKA mongodb+srv://). A and CNAME record lookups use .NET’s built-in capabilities and don’t require any third-party libraries. (Unfortunately these built-in capabilities do not include SRV and TXT record lookups, which is why we depend on DnsClient.NET for these record types.)

Please let us know if this workaround is successful for you.

Sincerely,
James

1 Like

Hi @James_Kovacs, thank you for your reply. I have tried to no avail the suggested workaround and I keep getting the same exception when running this line:

var client = new MongoClient("mongodb://user:password@127.0.0.1:27017");

I apologize if I’m misunderstanding something from the provided documentation.

this will try to connect tolocalhost, in this case to your Android’s own network. it won’t work. you need to give addresses to your mongodb servers. something like this:

mongodb://name:password@machine1:port1,machine2:port2,machine3:port3

you can say, DNS resolution is basically resolves mongo+srv://main_set_address to this format to find each member’s address.

check this for more info on connection strings: Connection String URI Format — MongoDB Manual

The fastest way to get working connaction string in mongodb:// format:

  • browse to your cluster’s Atlas page in a browser
  • open your project and head to “deployment->database” in the menu to the left.
  • click on “connect” button to the right of cluster name
  • select “connect your application” and then “C#/.NET”
  • select version “2.3 or earlier”. this will give you the url in the format I mentioned above.
    • edit it to have extrapolation :wink:

Yes, I know the local address won’t work, I also tried the actual address. But even if I use the local address it shouldn’t break the execution with the System.TypeInitializationException, just throw a connection error.

I cannot use mongo+srv://main_set_address because that would not be a standard connection string format as mentioned in the workaround from @ James_Kovacs. As I understood from his reply it should not include the +srv but I’m not sure of what else it entails. Also, just removing it from the one provided from the cluster’s Atlas page does not work in normal .dotnet client where it otherwise does work.

please read my answer, just one above your last response to get the “standard” connection string you need. that should get your app up and running. report back if your problem continues even with that.

Sorry, I skipped the select version when reading your reply. Thank you for your help.

So the code ends up looking like this:

string standardString = $"mongodb://{user}:{secret}@{shard0},{shard1},{shard2}/?ssl=true&replicaSet={replicaShard}&authSource=admin&retryWrites=true&w=majority";
var settings = MongoClientSettings.FromConnectionString(standardString);
_client = new MongoClient(settings);

This still works fine in dotnet 6, but still throws System.TypeInitializationException in Xamarin.

the error you are getting now might have something different. can you share what comes out now? try formatting to look nicers as I did before :wink:

Sure,

{System.TypeInitializationException: The type initializer for 'MongoDB.Driver.Core.Misc.DnsClientWrapper' threw an exception. ---> System.AggregateException: Error resolving name servers (Object reference not set to an instance of an object.) (Could not find file "/etc/resolv.conf") ---> System.NullReferenceException: Object reference not set to an instance of an object.
  at DnsClient.NameServer.QueryNetworkInterfaces () [0x0004c] in <519bb9af32234e5dba6bd0b076a88151>:0 
  at DnsClient.NameServer.ResolveNameServers (System.Boolean skipIPv6SiteLocal, System.Boolean fallbackToGooglePublicDns) [0x0005e] in <519bb9af32234e5dba6bd0b076a88151>:0 
   --- End of inner exception stack trace ---
  at DnsClient.NameServer.ResolveNameServers (System.Boolean skipIPv6SiteLocal, System.Boolean fallbackToGooglePublicDns) [0x00192] in <519bb9af32234e5dba6bd0b076a88151>:0 
  at DnsClient.LookupClient..ctor (DnsClient.LookupClientOptions options, DnsClient.DnsMessageHandler udpHandler, DnsClient.DnsMessageHandler tcpHandler) [0x000bc] in <519bb9af32234e5dba6bd0b076a88151>:0 
  at DnsClient.LookupClient..ctor (DnsClient.LookupClientOptions options) [0x00000] in <519bb9af32234e5dba6bd0b076a88151>:0 
  at DnsClient.LookupClient..ctor () [0x00006] in <519bb9af32234e5dba6bd0b076a88151>:0 
  at MongoDB.Driver.Core.Misc.DnsClientWrapper..ctor () [0x00006] in <b4b75168888d44e1ac6b514244ab7a7d>:0 
  at MongoDB.Driver.Core.Misc.DnsClientWrapper..cctor () [0x00000] in <b4b75168888d44e1ac6b514244ab7a7d>:0 
   --- End of inner exception stack trace ---
  at MongoDB.Driver.Core.Configuration.ConnectionString..ctor (System.String connectionString) [0x00000] in <b4b75168888d44e1ac6b514244ab7a7d>:0 
  at MongoDB.Driver.MongoUrlBuilder.Parse (System.String url) [0x00000] in <27273b0202ea4c34867b683ed7b21818>:0 
  at MongoDB.Driver.MongoUrlBuilder..ctor (System.String url) [0x00006] in <27273b0202ea4c34867b683ed7b21818>:0 
  at MongoDB.Driver.MongoUrl..ctor (System.String url) [0x00000] in <27273b0202ea4c34867b683ed7b21818>:0 
  at MongoDB.Driver.MongoClientSettings.FromConnectionString (System.String connectionString) [0x00000] in <27273b0202ea4c34867b683ed7b21818>:0 
  at  --FILENAME-- }

It seems to me that it is still using a dns lookup, despite the standard connection string format.

this line still boils hot. parts of libraries tries to fetch from that file and Android does not have that. it is not something specific to MongoDB.Driver either. I have met an issue on github related to MAUI. anyway, I get to this topic from a year and a half ago: c# - Last version of MongoDB.Driver not working for Android 8+: Could not find file “/etc/resolv.conf” - Stack Overflow.

Interpreting that post, they resolved with an older driver version at the time, I suggest you try lowering your driver version, a major version at a time, and see if you can find a working one within your project’s dotnet version. and also from @James_Kovacs answer above, depending on another library, you should not expect a resolution on newer versions anytime soon (maybe never, but I feel optimistic)

I’ve rolled back the driver version to 2.4.4 and it seems to work using the standard format. By 2.5.0 it doesn’t break but doesn’t work (timeouts). I’ll keep an eye on any further releases but I am a bit inclined to rework this into using the Atlas Data API. Still not sure if I’ll change it I but can say at least that the 2.4.4 version of the driver does work with the standard format and Android 12 and Xamarin forms 5

1 Like

Hey did you ever find another fix to this? I cannot roll back my drivers but am running into the same issue now. Did you just wind up using the Atlas Data API instead of the Drivers?

Hi, I’d recommend the Data API if rolling back is not an option… I moved to working on some other features in the meantime but I do want to eventually move to using http calls to the Data API. I find it more platform agnostic in case I ever need to move away from Xamarin for some reason. For now my connection is still the Mongo Driver in 2.4.4.

Okay gotcha, I appreciate the response. I think I have gotten the Realm SDK to work in Xamarin w/ Device Syncing which was my end goal so I’ll just ignore the .NET Drivers for now and possibly look at the Data API later on if need be. Thanks