Multiple Realms In Single App

I have a service app that needs to store information locally about its current run state. This information should NOT be synced back to Atlas.

I created a new Realm object to represent the state and did not add it to the sync subscriptions. Run the app to test it but I get exceptions saying that I can’t modify my schema unless I’m in developer mode.

Okay… I can’t write un-synced collections to a Realm that has synced collections… That’s annoying but understandable.

I create a new in-memory Realm specifically to hold the local state collection and plan to use that to hold the state data. I get the same exception which is confusing because I didn’t try to read or write any of the new collection’s information from the synced realm. Do some reading and discover that by default anything implementing IRealmObject is automatically added to your local Realm.

Okay… that’s a nice feature. But I don’t want it right now… Read more documentation…

There’s an IgnoredAttribute that will let a class be ignored which seems to be what I want. But if I add that attribute then I get compiler errors because that means it no longer has the default implementation of IRealmObject. I do still want that, just for my secondary Realm instead of the primary one.

Hit the search engine and see that there at least used to be a ```shouldIncludeInDefaultSchema` property/method in at least some SDK versions that would prevent that from being created in the main schema. That’s nice. I like that.

Nothing in the .NET SDK docs to support that. Annoying…

So what is the best way to exclude a single class from the default Realm and then include only it in the in-memory Realm?

I’m thinking

  • I create a custom class attribute that tells me that a Realm class is in-memory only
  • I use reflection to get my list of Realm classes that do not have that attribute set
  • When instantiating the primary database, declare a Schema in the Configuration with that list of classes
  • When instantiating the in-memory database, declare a Schema in the Configuration with only the classes that have the attribute set

Is that overkill? Is there a better way?

There’s an ExplicitAttribute that you can annotate your model with. That way it’ll be excluded from the default schema, but you can still add it explicitly in your in-memory schema.