Max A
Max A

Reputation: 21

Get custom attributes across assemblies

I have Assembly A, where MyCustomAttribute is located.

Now I have Assembly B, where I have reference to assembly A and I use in assembly B MyCustomAttribute.

Now I want to get all inctanses of MyCustomAttribute in Assebmly B.

I try something like:

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

And other ways -- but I can't get MyCustomAttribute.

UPDATE

My attribute

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

Upvotes: 0

Views: 1079

Answers (2)

zaitsman
zaitsman

Reputation: 9499

Try this:

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

Upvotes: 0

Sumit Maingi
Sumit Maingi

Reputation: 2263

I tried this:

public class MyCustomAttribute : Attribute
{
}

[MyCustom]
public class SomeClassWithAttribute
{

}

Then in the console:

var assembly = typeof(SomeClassWithAttribute).Assembly;

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

I get SomeClassWithAttribute with in the types list. @C.Evenhuis is correct, you are probably getting the wrong assembly in the "GetCallingAssembly" method. Its always more reliable to get an assembly by getting a type that you know is present in that assembly and then getting the Assembly property from that.

Upvotes: 1

Related Questions