Which assembly do I want?
I'm writing a web framework, and I'm implementing some custom attributes. I want to get all of those attributes so that I can do something with them. I guess to do that, I first need to get the assembly, and then I can get all the types (classes) defined in it, and from there I can get all its methods, and then finally the attributes.
So, I'm looking at Assembly.Get___Assembly
. Do I want to use Calling, Entry, or Executing? This webframework will get compiled into its own assembly DLL, and then people using the framework should include that DLL and implement their own classes using attributes from the web framework assembly.
So... I was thinking Executing would give me the web framework DLL because thats where the attribute-handling code is, but not where the attributes are used, 开发者_如何转开发so thats not what I want.
EntryAssembly sounds promising... but this is running over IIS.... so what would it return?
And CallingAssembly just sounds wrong... so which do I want?
Presently, I haven't separated the webframework into its own assembly yet, so I'm kind of building a web app and a web framework simultaneously in one assembly.
So ExecutingAssembly
does work (for now) but I'm afraid when I separate it out it will give me the wrong one.
CallingAssembly
gives System.Web
, and EntryAssembly
is null, for whatever reason.
If all the elements that are decorated with this attribute are in the same assembly as the calling code, you can just use this.GetType().Assembly
(or typeof(CurrentType).Assembly
for statics).
The other common scenario is acquiring all attribute-decorated elements in the application regardless of assembly, which is easily done via AppDomain.CurrentDomain.GetAssemblies()
.
I think the safest option here is to let the users of your framework specify the assembly they want:
SomeClass.RegisterAssembly(this.GetType().Assembly);
(where SomeClass
is defined in your framework)
Here's the code I ended up using to get all my attributes:
*snip*
New version:
private static IEnumerable<Route> GetInlineRoutes()
{
var methods = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a =>
a.GetTypes()
.Where(t => t.IsClass && t.IsSubclassOf(typeof (Controller))))
.SelectMany(c => c.GetMethods(BindingFlags.Public | BindingFlags.Instance));
return from method in methods
let urlAttributes = method.GetCustomAttributes(true).OfType<UrlAttribute>()
from attr in urlAttributes
select new Route(attr.Pattern, method, attr.Priority);
}
精彩评论