2016-12-30 25 views
0

我有程序集A,其中MyCustomAttribute位于。跨程序集获取自定义属性

现在我有大会B,在那里我有reference组装A和我在组装BMyCustomAttribute使用。

现在我想获得的所有MyCustomAttribute在inctanses B. Assebmly

我尝试类似:

public static void Registration() 
{ 
    List<MyCustomAttribute> atrr = new List<MyCustomAttribute>(); 

    var assembly = System.Reflection.Assembly.GetCallingAssembly(); 

    var types = (from type in assembly.GetTypes() 
        where Attribute.IsDefined(type, typeof(MyCustomAttribute)) 
        select type).ToList(); 
} 

等方式 - 但我不能让MyCustomAttribute

UPDATE

我的属性

namespace NamespaceOne.Attributes 
{ 
    [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false, 
    Inherited = false)] 
    public class MyCustomAttribute: Attribute 
    { 
     ...... 
    } 
} 

Now the second Assembly(second project - ASP WebApi): 

namespace SecondNamespace.Controllers 
{ 
    public class HomeController : Controller 
    { 

     [MyCustomAttribute] 
     public ActionResult Index() 
     { 
     MyStaticMethod.Registration(); // THIS Class andmethod in First class library - where located attribute 
      ViewBag.Title = "Home Page"; 

      return View(); 
     } 
+2

你验证'GetCallingAssembly()'实际上返回'B'? –

+0

是的。但在里面我没有看到我的自定义属性 –

+0

你可以显示你的属性,以及实现它的类型? – Bauss

回答

1

我尝试这样做:在控制台

public class MyCustomAttribute : Attribute 
{ 
} 

[MyCustom] 
public class SomeClassWithAttribute 
{ 

} 

然后:

var assembly = typeof(SomeClassWithAttribute).Assembly; 

      var types = (from type in assembly.GetTypes() 
         where Attribute.IsDefined(type, typeof(MyCustomAttribute)) 
         select type).ToList(); 

我在类型列表中得到了SomeClassWithAttribute。 @ C.Evenhuis是正确的,你可能在“GetCallingAssembly”方法中得到错误的程序集。通过获得一个你知道的类型来获得一个程序集,然后从该程序集中获取Assembly属性,它总是更加可靠。

+0

Attribyte和方法,其中我在不同的程序集中使用此属性 –

+0

您需要一些其他方式来获取目标程序集...是找到该类型的方法始终查找特定程序集或其通用方法的方法?如果它的泛型,它是否总是应该返回它应该在调用代码的程序集中找到的属性? –

0

试试这个:

public static void Registration() 
{ 
    List<RegistryAttribute> atrr = new List<RegistryAttribute>(); 

    var assembly = System.Reflection.Assembly.GetCallingAssembly(); 

    var types = assembly.GetTypes().Where(type => 
        type.GetCustomAttributes().Any(x => x is typeof(MyCustomAttribute))).ToList(); 
}