Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6720295
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T09:11:44+00:00 2026-05-26T09:11:44+00:00

How can I write a PostSharp aspect to apply an attribute to a class?

  • 0

How can I write a PostSharp aspect to apply an attribute to a class? The scenario I’m considering is a WCF entity (or domain object) that needs to be decorated with the DataContract attribute. It should also have a Namespace property. Like this:

using System.Runtime.Serialization;

namespace MWS.Contracts.Search.V1
{
    namespace Domain
    {
        [DataContract(Namespace = XmlNamespaces.SchemaNamespace)]
        public class PagingContext
        {
            [DataMember]
            public int Page { get; set; }

            [DataMember]
            public int ResultsPerPage { get; set; }

            [DataMember]
            public int MaxResults { get; set; }
        }
    }
}

In the above example you can see what I want the output to look like. It has the DataContract attribute applied to the class. Doing this by hand is tedious and not unique. I’d really just like to write a single aspect that can be applied a my “Domain” namespace. It would then apply the serialization related attributes for me. This way I can just focus on developing entity objects, and not worry about the serialization pluming details.

I have found documentation on PostSharp’s website for injecting code before, after, and instead of methods. However what I’m looking for is a way to inject an Attribute onto a type.


Here is the solution!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using PostSharp.Aspects;
using PostSharp.Extensibility;
using PostSharp.Reflection;

namespace MWS.Contracts.Aspects
{
    // We set up multicast inheritance so  the aspect is automatically added to children types.
    [MulticastAttributeUsage(MulticastTargets.Class, Inheritance = MulticastInheritance.Strict)]
    [Serializable]
    public sealed class AutoDataContractAttribute : TypeLevelAspect, IAspectProvider
    {
        private readonly string xmlNamespace;

        public AutoDataContractAttribute(string xmlNamespace)
        {
            this.xmlNamespace = xmlNamespace;
        }

        // This method is called at build time and should just provide other aspects.
        public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
        {
            var targetType = (Type) targetElement;

            var introduceDataContractAspect =
                new CustomAttributeIntroductionAspect(
                    new ObjectConstruction(typeof (DataContractAttribute).GetConstructor(Type.EmptyTypes)));

            introduceDataContractAspect.CustomAttribute.NamedArguments.Add("Namespace", xmlNamespace);

            var introduceDataMemberAspect =
                new CustomAttributeIntroductionAspect(
                    new ObjectConstruction(typeof (DataMemberAttribute).GetConstructor(Type.EmptyTypes)));

            // Add the DataContract attribute to the type.
            yield return new AspectInstance(targetType, introduceDataContractAspect);

            // Add a DataMember attribute to every relevant property.)))
            foreach (var property in
                targetType.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance)
                    .Where(property =>
                           property.CanWrite &&
                           !property.IsDefined(typeof (NotDataMemberAttribute), false)))
                yield return new AspectInstance(property, introduceDataMemberAspect);
        }
    }

    [AttributeUsage(AttributeTargets.Property)]
    public sealed class NotDataMemberAttribute : Attribute
    {
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T09:11:44+00:00Added an answer on May 26, 2026 at 9:11 am

    See http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-12-e28093-Aspect-Providers-e28093-Part-1.aspx

    Here is a working example. Applying this aspect to a class will apply the XmlIgnore attribute to any public property that does not already have XmlElement or XmlAttribute applied to it. the trick is using the CustomAttributeIntroductioinAspect that is built in to Postsharp. You just need to instantiate an instance specifying the attribute type and contructor details, then create a provider to apply it to the target(s).

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using PostSharp.Extensibility;
    using PostSharp.Aspects;
    using PostSharp.Reflection;
    using System.Xml.Serialization;
    
    namespace ApplyingAttributes
    {
        [MulticastAttributeUsage(MulticastTargets.Field | MulticastTargets.Property,
                                TargetMemberAttributes = MulticastAttributes.Public | MulticastAttributes.Instance)]
        public sealed class AddXmlIgnoreAttribute : LocationLevelAspect, IAspectProvider
        {
            private static readonly CustomAttributeIntroductionAspect customAttributeIntroductionAspect =
                new CustomAttributeIntroductionAspect(
                    new ObjectConstruction(typeof(XmlIgnoreAttribute).GetConstructor(Type.EmptyTypes)));
    
            public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
            {
                LocationInfo memberInfo = (LocationInfo)targetElement;
    
                if (memberInfo.PropertyInfo.IsDefined(typeof(XmlElementAttribute), false) ||
                    memberInfo.PropertyInfo.IsDefined(typeof(XmlAttributeAttribute), false))
                    yield break;
    
                yield return new AspectInstance(memberInfo.PropertyInfo, customAttributeIntroductionAspect);
            }
        }
    
    }
    

    To use attributes, specifying parameters, I use

     public class MyAspect : TypeLevelAspect, IAspectProvider
    {
        public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
        {
            yield return Create<MethodInfo>(mi, "Value");
    
        }
    
        private AspectInstance Create<T>(T target, string newName)
        {
            var x = new CustomAttributeIntroductionAspect(
                new ObjectConstruction(typeof(NewMethodName).GetConstructor(new Type[] { typeof(string) }), new object[] { newName })
                );
    
            return new AspectInstance(target, x);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How can write a method that can be used to instantiate an object through
Can someone please explain how you can write a url pattern and view that
In SQL one can write a query that searches for a name of a
I can write a ejb like this... @Stateless public class AnotherBean { @PersistenceContext(unitName =
How i can write a PHP file that overwrites .htaccess with the correct information?
i can write methods like that public void CompareEmail() { some code } public
I can write a predicate that is satisfied when two lists are equal e.g.
In c++ we can write: #include <iostream> class Base1 { public: void test() {
How can write a print statement in python that will print exactly 2 digits
I can write some links: <p>This value is 23456. <a class=edit href=# custom-data=2356>Edit</a></p> <p>This

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.