In this post I will show how you can create an attribute of your own, that you can use on properties and/or parameters, which will make
ObjectBuilder setting the value of the property or parameter. So lets say that you want to know what kind of permission a user has so you have a property in your class that looks something like this:
public PermissionLevel Permission
{
get { returnthis.permissionLevel; }
set { this.permissionLevel = value; }
}
PermissionLevel is an enumeration and to simplify it all lets say it has two values; Read and ReadWrite. Now if you want this property to be set by ObjectBuilder, you could set a policy that a property with the name of Permission should get this value. The downside with this is of course that it will require the property to be named Permission and in this example I am showing you how to create an attribute so that’s the second option. The attribute should inherit from ParameterAttribute (defined in ObjectBuilder) and could look something like this:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
public sealed class PermissionAttribute : ParameterAttribute
{
public override IParameter CreateParameter(Type memberType)
{
return new PermissionParameter();
}
private class PermissionParameter : IParameter
{
string taskId;
public PermissionParameter(string taskId)
{
this.taskId = taskId;
}
public Type GetParameterType(IBuilderContext context)
{
return typeof(PermissionLevel);
}
public object GetValue(IBuilderContext context)
{
// Put your logic here.
if (Thread.CurrentPrincipal.IsInRole("Administrator"))
return PermissionLevel.ReadWrite;
else
return PermissionLevel.Read;
}
}
}
The key here is to override CreateParameter (defined in ParameterAttribute) and return a class that implements IParameter interface. The GetParameterType function should return the type and GetValue the value that the property or parameter should be set to. To keep it all simple I just check if the user is in the Administrator role and in that case returns ReadWrite otherwise Read. Apply this attribute to the property above and create the class containing the property with the help of ObjectBuilder and it will set its value depending on the role you belongs too.
In a more realistic scenario you might be dependent of a custom principal object where you could ask for the users permission to a specific task. To identify which task to ask for you would put a property in the attribute that could be set. Still this simplified example shows you how to create your own attributes that you could apply to properties and parameters so that they will be injected by ObjectBuilder. Only you know which attributes you want to create :).