public
Created

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
using System;
using System.Reflection;
using PostSharp.Aspects;
using PostSharp.Extensibility;
using NUnit.Framework;
 
namespace Examples
{
public interface IServiceWithDependency
{
int SomeValue { get; set; }
}
 
[Serializable]
public class InjectedAspectAttribute : MethodInterceptionAspect
{
public override bool CompileTimeValidate(MethodBase method)
{
var result = true;
var methodInfo = method as MethodInfo;
 
if (!typeof(IServiceWithDependency).IsAssignableFrom(method.DeclaringType))
{
Message.Write(methodInfo, SeverityType.Error, "999", string.Format("Only class derived from IServiceWithDependency allowed, {0} not implements IServiceWithDependency", method.DeclaringType));
 
result = false;
}
 
return result;
}
 
public override void OnInvoke(MethodInterceptionArgs args)
{
if (args.Instance is IServiceWithDependency)
{
(args.Instance as IServiceWithDependency).SomeValue = 123;
}
 
args.Proceed();
}
}
[TestFixture]
public class InjectedAspectTests
{
[Test]
public void InjectedAspect_Dependency_Should456123()
{
// Arrange
var sut = new MyClass();
 
// Act
var result = sut.DoSomething();
 
// Assert
Assert.That(result, Is.EqualTo("456123"));
}
 
public class MyClass : IServiceWithDependency
{
public int SomeValue { get; set; }
 
[InjectedAspect]
public string DoSomething()
{
string otherValue = "456" + SomeValue;
 
return otherValue;
}
}
 
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.