简体   繁体   中英

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM