First of all: I am not very educated about disposing object and the ways to do it.
The project:
Currently I am working on a solution that includes an ASP.Net API, WPF and library project (all in .NET 6.0). The library contains .resx files to provide localized strings. I have implemented the localization according to this guide. This works pretty well except in some cases. The main problem is in the WPF project. I will simplify the namespaces to make them more accessible:
- WPF project:
My.Namespace.WPF - Library project:
My.Namespace.Language
To get all supported languages, I use this class in My.Namespace.Language:
public class LanguageProvider
{
public static IEnumerable<CultureInfo> GetSupportedLanguages()
{
List<CultureInfo> supportedLanguages = new();
CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures);
foreach (CultureInfo culture in cultures)
{
try
{
using ResourceSet? rs = Resources.Strings.ResourceManager.GetResourceSet(culture, true, false);
if (rs is not null && culture.TwoLetterISOLanguageName != "iv")
{
if (!supportedLanguages.Contains(culture))
{
supportedLanguages.Add(culture);
}
}
else if (culture.TwoLetterISOLanguageName == "en")
{
supportedLanguages.Add(culture);
}
}
catch (Exception)
{
}
}
return supportedLanguages;
}
}
This project also contains the resource folder with Strings.resx and Strings.de.resx (namespace My.Namespace.Language.Resources). To get a string from the resources in my WPF project, I just use this:
string customText = My.Namespace.Language.Resources.Strings.sometext;
The problem:
All objects that are initalized after the first call of GetSupportedLanguages() cannot access the Strings and throw an ObjectDisposedException: Cannot access a closed resource set. Normally it is called before the MainWindow is initialized. So therefore I could not even display that. Do I have to implement the listing of available languages differently because the resources are disposed at some point?
Apparantly, you should not dispose the
ResourceSetto be able to re-use theResourceManagerto get the resources. Removeusing: