Reputation: 9915
Is there a way to have extension method on the method? Example for this would be method that takes some user object as parameter and you need to do security check if that user can use that method at the very beginning of the method. Can the method have extension method like "check can this user use me" and return bool.
Thanks.
Upvotes: 5
Views: 934
Reputation: 49970
You can't add extension method for a method with C#.
But you could use Aspect Oriented Programming (AOP) to do what you want, using PostSharp or Spring.NET for example.
Example of securing methods with PostSharp
public class BusinessDivision : BusinessObject
{
[SecuredOperation("Manager")]
public void EnlistEmployee(Employee employee)
{
// Details omitted.
}
}
Upvotes: 3
Reputation: 19956
You can go with madgnome's answer, which is based on aspect programming (glad to see that somebody used that in .net) or you can use attributes and paste some code in every method that should be guarded.
Upvotes: 0
Reputation: 106796
You can use Aspect Oriented Programming (AOP) to implement cross-cutting security checks in your code.
In .NET you have a choice of several AOP frameworks, for example:
In particular the PostSharp documentation has some nice examples on how to implement security using AOP.
Upvotes: 7
Reputation: 498904
Extension methods in C# are not extensions of methods (not sure I understand what that means), but methods that extend objects/classes.
If you want to inject the kind of checks you are describing into your code, you can look into PostSharp and AOP.
Upvotes: 0
Reputation: 27962
I'm not sure if I understand your question well. However, what about this:
public static void EnsureUserHasAccess(this object obj)
{
// check permissions, possibly depending on `obj`'s actual type
}
public static void DoSomething(this MyClass obj)
{
// permissions check
obj.EnsureUserHasAccess();
// do something about `obj`
…
}
public static void DoSomethingElse(this MyDifferentClass obj)
{
// permissions check
obj.EnsureUserHasAccess();
// do something about `obj`
…
}
Upvotes: 0
Reputation: 3318
I am not quite sure what you are looking for but this smells like declarative security to me.
Take a look at: http://msdn.microsoft.com/en-us/library/kaacwy28.aspx
Upvotes: 0