I have a class like this:
public class LocalizedDataAnnotationsModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
Func<object> modelAccessor, Type modelType, string propertyName)
{
var meta = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
if (string.IsNullOrWhiteSpace(propertyName))
return meta;
if (meta.DisplayName == null)
GetLocalizedDisplayName(meta, propertyName);
if (string.IsNullOrWhiteSpace(meta.DisplayName))
{
string resource = string.Format("{0}_{1}", meta.ContainerType.Name, meta.PropertyName).ToLower();
meta.DisplayName = string.Format("[{0}]", resource);
}
return meta;
}
private static void GetLocalizedDisplayName(ModelMetadata meta, string propertyName)
{
ResourceManager rm = new ResourceManager(typeof (i18n));
CultureInfo culture = Thread.CurrentThread.CurrentUICulture;
string resource = string.Format("{0}_{1}", meta.ContainerType.Name, meta.PropertyName).ToLower();
meta.DisplayName = rm.GetString(resource, culture);
}
}
I want to abstract away the line
ResourceManager rm = new ResourceManager(typeof (i18n));
I want to make this class indenpendent of the type i18n. I want to be able to specify the type for the resource manager at construction/initialization, making the class more universal and put it in a standalone class library.
What are my options? Can it be done with a static class or do I have to have non-static class? Or can I just leave the way it is, abstract the rm as class field and initialize it in the constructor?
Thank you
UPDATE: Please note the class will most likely be used in various ASP.NET MVC sites in global.asax.cs like this:
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
ModelMetadataProviders.Current = new LocalizedDataAnnotationsModelMetadataProvider();
}
I am never actually referencing or using this class directly, ASP.NET MVC does everything under the hood.
You can make the class generic:
And set it up like this: