Como criar um Custom Configuration Section em .NET 2.0

Quando se cria uma aplicação em .NET naturalmente se utiliza arquivos de configuração .config para centralizar e organizar sua estrutura. Normalmente web.config e app.config.

Muitas vezes se utiliza as seções appSettings e connectionStrings para configurações manipulados via código. Mas também é possível customizar os blocos destas configurações.
O que é necessário?

  1. Uma classe que herde de System.Configuration.ConfigurationSection
  2. Uma referencia no config no elemento <configSections>
  3. Utilização do configSectionCustomizado
  4. Consumir o valor do configSectionCustomizado
Então vamos lá…
1 – Como criar a uma classe ConfigurationSection
using System.Configuration;
namespace ConfigSection
{
    public class AnselmeSection : ConfigurationSection
    {
        [ConfigurationProperty(“AnselmeServer”, DefaultValue = “anselme://mail.sx”, IsRequired = true)]
        public String AnselmeServer
        {
            get
            {
                return (String)this[“AnselmeServer”];
            }
            set
            {
                this[“AnselmeServer”] = value;
            }
        }
    }
}

2 – Como criar uma referencia no <configSections>

<configSections>

      <section name=Anselme type=ConfigSection.AnselmeSection, ConfigSection/>

</configSections>

3 – Como utilizar o configSection customizado no .config ?
  <Anselme AnselmeServer=anselme://brazil.mail.op />

4 – Como consumir este código?
namespace ConfigSection
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AnselmeSection config = (AnselmeSection)ConfigurationManager.GetSection(“Anselme”);
            string servidor = config.AnselmeServer;
        }
    }
}

Para mais detalhes, a referecia oficial é:
http://msdn.microsoft.com/en-us/library/2tw134k3.aspx


Thiago Anselme
Thiago Anselme - Gerente de TI - Arquiteto de Soluções

Ele atua/atuou como Dev Full Stack C# .NET / Angular / Kubernetes e afins. Ele possui certificações Microsoft MCTS (6x), MCPD em Web, ITIL v3 e CKAD (Kubernetes) . Thiago é apaixonado por tecnologia, entusiasta de TI desde a infância bem como amante de aprendizado contínuo.

Deixe um comentário