Coder Social home page Coder Social logo

simple-config's Introduction

simple-config

Simple-config is an extensible, convention-based XML to C# binder, specifically designed to easily bind custom config sections without the need to write any config handlers or sections.

Simply by performing a cast to the required type, SimpleConfig will perform all required mapping, without the use for any magical markup.

Nuget Nuget Build status

##Simple use case

If we have some configurable settings

public class ServiceSettings
{
  public int MaxThreads { get; set; }
  public string Endpoint { get; set; }
  public IEnumerable<string> BannedPhrases { get; set; }
}

we could write the xml for it in our app.config or web.config

<!-- Wire up the handler inside the <configSections /> element; once per custom section -->
<section name="serviceSettings" type="SimpleConfig.SimpleConfigHandler, SimpleConfig" />

<!-- And this goes in the main part of the config file -->
<serviceSettings maxThreads="4">
  <endpoint>http://localhost:9090</endpoint>
  <bannedPhrases>
    <phrase>something</phrase>
    <phrase>else</phrase>
  </bannedPhrases>
</serviceSettings>

We could now write a disproportionately large ConfigurationSection, or a some boilerplate code, or we could just call this:

var settings = (ServiceSettings)(dynamic)ConfigurationManager.GetSection("serviceSettings");

or even

ServiceSettings settings = (dynamic)ConfigurationManager.GetSection("serviceSettings");

##Binding to interfaces As of version 1.2 (Nov 2014), it is possible to bind to a pure interface (a concrete class will be create for you). The binding copes with subinterfaces and multiple inheritence too; you just need to remember the following points:

* Your interface cannot define any methods
* Each property must define a getter (setters are optional)
* You must use implicit binding to invoke the mapper:
IServiceSettings settings = (dynamic)ConfigurationManager.GetSection("serviceSettings");

##Overriding the default conventions If you don't mind using attributes, Simple-config does come with some a small selection of binding hints to guide the binding process. For example, using the same xml as above, the following settings DTO could still be bound:

public class ServiceSettings
{
  public int MaxThreads { get; set; }
  public string Endpoint { get; set; }
  
  [CustomEnumerable("bannedPhrases")]  //magic
  public IEnumerable<string> PhrasesThatAreBanned { get; set; }
}

##Enumerables and lists Simple-config is designed to be helpful when binding IEnumerables; please consider the following when binding:

  • You destination needs to implement System.Collections.Generic.IEnumerable<> so that the payload type is known
  • You can only bind to IEnumerable<> if the destination property has a setter (so SimpleConfig can create a mutatable Type)
  • If your destination property has no setter, it needs to be pre-populated with something that implements ICollection<>

##Do anything

The architecture of Simple-config allows you to create new binding strategies to perform whatever custom binding you need, for example, to decrypt sensitive config

Simply create a binding stratgy that implements IBindingStrategy

/// <summary>
/// Details a specific strategy for populating an object based on the config
/// </summary>
public interface IBindingStrategy
{
    /// <param name="destinationObject">The instance of the object ot be populated</param>
    /// <param name="destinationProperty">The property to be populated</param>
    /// <param name="element">The config element at the level we are mapping</param>
    /// <param name="allConfig">The entire config dom, as provided to the config handler</param>
    /// <param name="mapper">The current config mapper</param>
    /// <returns>Whether or not the binding was successful</returns>
    bool Map(object destinationObject, PropertyInfo destinationProperty, XmlElement element, XmlElement allConfig, ConfigMapper mapper);
}

In order to hook up the binding strategy, create a new binding attribte that inherits BaseBindingAttribute

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public abstract class BaseBindingAttribute : Attribute
{
    public abstract IBindingStrategy MappingStrategy { get; }
}

Then attach the binding attribute to the property that requires custom binding.

simple-config's People

Contributors

fnasimbd avatar jameshulse-justgiving avatar spadger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

simple-config's Issues

Import dictionary

How should the config file be arranged to import a dictionary (eg. IDictionary<double, string>)?

Complex Types?

If I have:

public class ApiKeyUser
{
    public string ApiKey { get; set; }
    public string Name { get; set; }
    public IEnumerable<string> Roles { get; set; }
}
public class ApiKeyUsers
{
    public IEnumerable<ApiKeyUser> Users { get; set; }
}

Is this supported:
ApiKeyUsers foo = (dynamic)ConfigurationManager.GetSection("ApiKeyUsers");

Assuming I have configured:

<section name="ApiKeyUsers" type="SimpleConfig.SimpleConfigHandler, SimpleConfig" />
...
<ApiKeyUsers>
  <ApiKeyUser Name="Foo" ApiKey="1234567890abcdefghijklm">
    <Roles>
      <Role>ApiReader</Role>
      <Role>ApiWriter</Role>
    </Roles>
  </ApiKeyUser>
</ApiKeyUsers>

How to use Simple-Config

I tried to use simple-config but on the dynamic cast of the section I'm having the error:

" does not inherit from 'System.Configuration.IConfigurationSectionHandler"

I'm sure it must be something very easy, but I'm finding difficult to find it.
Isn't there a tutorial of how to use Simple-Config?

Thanks

Problem with Travis

I try a pull request, but it look like the .travis.yaml file is missing. So, the CI integration dosn't work.
Thanks.

Create Internal Interfaces?

This works fine with internal classes, but when I try to use an internal interface as settings container, I get Type 'SimpleConfig.Dynamic.InterfaceImplementations._MyAssembly.IServiceSettings_Impl' from assembly 'SimpleConfig.Dynamic.InterfaceImplementations, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.

I've tried to make my InternalsVisibleTo "SimpleConfig", but that doesn't help. Any idea?

Default values

How may I include default values for each configurable value, to be used in the case that the config file was invalid?

I get an error during compilation of my solution: Assembly generation failed -- Referenced assembly 'SimpleConfigSections' does not have a strong name

I get an error during compilation of my solution: Assembly generation failed -- Referenced assembly 'SimpleConfigSections' does not have a strong name

The reason for this is that you didn't use strong naming to sign your assembly. This means I'm forced to use a different kind of Configuration library. Not strong naming my own solution is out of the question.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.