Using configuration settings in attributes

I have a C # code snippet that looks like this:

[OracleCustomTypeMapping(Constants.DBSchema + ".TAB_VARCHAR2_250")] public class StringTableFactory : TableFactoryTemplate<StringTable> { public override System.Array CreateStatusArray(int length) { return new OracleUdtStatus[length]; } } 

Is there a way to change the attribute declaration, so Constants.DBSchema is read from web.config instead of being hardcoded as a constant in the code? If I put ConfigurationManager.appSettings in the attribute declaration, I get the message "The attribute argument must be a constant expression ...".

Thanks.

+4
source share
1 answer

Instead of passing it as part of the constructor arguments, read it directly from the ConfigurationManager in the attribute constructor.

 public class OracleCustomTypeMappingAttribute : Attribute { public OracleCustomTypeMappingAttribute(string typeName) { var schema = ConfigurationManager.AppSettings["Schema"]; TypeMapping = schema + "." + typeName; // Or whatever property needs to be set } } 

Then you just do:

 [OracleCustomTypeMapping("TAB_VARCHAR2_250")] public class StringTableFactory : TableFactoryTemplate<StringTable> { public override System.Array CreateStatusArray(int length) { return new OracleUdtStatus[length]; } } 
+8
source

Source: https://habr.com/ru/post/1500578/


All Articles