Add attribute to another assembly class

Is it possible to extend the type defined in another assembly to add an attribute to one of its properties?

For example, I have a FooBar assembly:

public class Foo { public string Bar { get; set; } } 

But in my assembly of user interfaces, I want to pass this type to a third-party tool, and for this third-party tool to work correctly. I need the Bar property to have a specific attribute. This attribute is defined in a third-party assembly, and I do not want to refer to this assembly in my FooBar assembly, since FooBar contains my domain, and it is a user interface tool.

+4
source share
4 answers

You cannot if a third-party tool uses standard reflection to get attributes for your type.

You can if a third-party tool uses the TypeDescriptor API to get attributes for your type.

Sample code for a type descriptor:

 public class Foo { public string Bar { get; set; } } class FooMetadata { [Display(Name = "Bar")] public string Bar { get; set; } } static void Main(string[] args) { PropertyDescriptorCollection properties; AssociatedMetadataTypeTypeDescriptionProvider typeDescriptionProvider; properties = TypeDescriptor.GetProperties(typeof(Foo)); Console.WriteLine(properties[0].Attributes.Count); // Prints X typeDescriptionProvider = new AssociatedMetadataTypeTypeDescriptionProvider( typeof(Foo), typeof(FooMetadata)); TypeDescriptor.AddProviderTransparent(typeDescriptionProvider, typeof(Foo)); properties = TypeDescriptor.GetProperties(typeof(Foo)); Console.WriteLine(properties[0].Attributes.Count); // Prints X+1 } 

If you run this code, you will see that the last console entry prints plus one attribute, because the Display attribute is also considered now.

+5
source

No. Cannot add attributes to types from individual assemblies.

However, you can create your own type that wraps a third-party type. Since you have full control over your wrapper class, you can add attributes there.

+1
source

What about:

 public class Foo { public virtual string Bar } public class MyFoo : Foo { [yourcustomattribute] public overrides string Bar } 
0
source

I think that you need some kind of adapter layer that will not allow this infrastructure dependency to flow into the logic of your domain. Perhaps you can create an adapter class that will be like a data transfer object of another technology. This class lives in an integration assembly that is dependent on a third-party library:

 public class FooDTO { [TheirAttribute] public string Bar { get; set; } } 

Then you can use something like AutoMapper to ease the pain of changing views.

The ideal solution, however, is that a third-party library supports additional ways to provide metadata about their actions. Perhaps you can ask them about this feature.

0
source

Source: https://habr.com/ru/post/1383718/


All Articles