Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Created January 6, 2013 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akimboyko/4468274 to your computer and use it in GitHub Desktop.
Save akimboyko/4468274 to your computer and use it in GitHub Desktop.
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;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment