Created
January 6, 2013 16:21
-
-
Save akimboyko/4468274 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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