views:

31

answers:

2

Are there any frameworks that assist me with this: (thinking that perhaps StructureMap can help me)

Whenever I create a new instance of "MyClass" or any other class that inherits from IMyInterface I want all properties decorated with [MyPropertyAttribute] to be populated with values from a database or some other data storage using the property Name in the attribute.

public class MyClass : IMyInterface
{
    [MyPropertyAttribute("foo")]
    public string Foo { get; set; }
}

[AttributeUsage(AttributeTargets.Property)]
public sealed class MyPropertyAttribute : System.Attribute
{
    public string Name
    {
        get;
        private set;
    }

    public MyPropertyAttribute(string name)
    {
        Name = name;
    }
}
A: 

Use an abstract class instead (or a factory pattern if you insist on an interface).

With an abstract class, you can just do the necessary population in the default constructor with a little bit of reflection.

Something like:

abstract class Base
{
  protected Base()
  {
    var actualtype = GetType();
    foreach (var pi in actualtype.GetProperties())
    {
      foreach (var attr in pi.GetCustomAttributes(
         typeof(MyPropertyAttribute), false))
      {
        var data = GetData(attr.Name); // get data
        pi.SetValue(this, data, null);
      }
    }
  }
}

Disclaimer: Code may not compile, I just wrote it from the top of my head.

leppie
A: 

Check the following frameworks from codeplex: http://www.codeplex.com/AutoMapper for mapping and http://fasterflect.codeplex.com/ for fast reflection to gather your properties and setvalues or getvalues.

Kerem Kusmezer