0

For mapping purposes I would like to pass a Func<> into attribute constructor, so that something like this would become possible:

[Map<Foo>(foo=>foo.Name)]
public string Name { get; set; }

I realize that attributes have to be compile-time constant, so it would be impossible to do this with pure C#.

I wonder if any PostSharp-like library exists to do something similar (judging by this post I guess there are ways to implement this in pure IL).

Community
  • 1
  • 1
bashis
  • 1,200
  • 1
  • 16
  • 35

1 Answers1

1

No way. You want two things that currently attributes doesn't support in C#:

  • Generic type parameters.
  • Non-constant arguments.

Think that attributes are just metadata, you can't expect to run nothing during its usage (obviously the attribute constructor may run whichever code you may add on it).

While the other Q&A you've linked mentions that emitting IL directly you should be able to do it, I'm also pretty sure that you can avoid adding complexity to your project implementing a fluent API:

public class A : IMappingConfigurator
{
     public string Name { get; set; }

     public void Configure(IMappingConfiguration config)
     {
          config.Map<Foo>(foo => foo.Name);
     } 
}

And during the configuration stage, you can get all types implementing the whole interface and instantiate them just to get the configuration of each one:

IEnumerable<IMappingConfigurator> configurators = Assembly.GetExecutingAssembly().GetTypes().Where
(
    t => t.GetInterfaces().Any(t => t == typeof(IMappingConfigurator))
).Select(t => (IMappingConfigurator)Activator.CreateInstance(t));
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206