i want use custom attribute on my n-tier project. for
-Caching- -Logging -Validation -Exception
i want use custom attribute on my n-tier project. for
-Caching- -Logging -Validation -Exception
First of all you should search for AOP. this is some kind of developing methodology
Aspect-Oriented Programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. Wikipedia
It is not as simple as you think,in C# you have to use some 3rd party Library.
I suggest to start with MrAdvice, it will helps you.
Writing your custom attributes would look a little something like this:
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method)]
public class LogAttribute : Attribute
{
public bool _loggingEnabled;
public LogAttribute(loggingEnabled)
{
_loggingEnabled = loggingEnabled;
}
}
Usage example:
[Log(true)]
public class SampleClass
{
}
If you require further clarification if you share a little bit more about your intended usage of the attributes I'd be able to clarify a bit more. For instance, I'm not sure if you wanted your logging attribute to give you a means to explicitly state if that class/struct would be logged, but that's how I decided to demonstrate this. Also, note you can apply that to properties, and various other members via the AttributeUsage
attribute on your attribute class declaration. I hope that helps.
Update:
Save method example:
[Log(true)]
public void Save(Company company)
{
_context.Save();
}
Then you'll use the static method Attribute.GetCustomAttribute(MemberInfo element, Type attributeType)
to retrieve information stored in that attribute. Since in this case, you'll likely want to use logging in many places you'd write another method (most likely static as well) somewhere else in your application that'd look something like this (see the link to the System.Reflection reference below for more information).
public static void Log(MemberInfo element)
{
LogAttribute attribute = Attribute.GetCustomAttribute(element, typeof(LogAttribute);
if (attribute._loggingEnabled)
{
// Create log file and add information from here.
}
}