ここでの回答で説明されている動作を取得したいと思いますが、コードを使用して構成を使用します。コード サンプルは、単一性に関連するものなしで作成され、構成を通じて動作を追加するカスタム属性を示しています。
カスタム属性は、同じソリューションで参照される別のアセンブリにあります。
問題は、構成中に例外がスローされることです。
InvalidOperationException: 型 Microsoft.Practices.Unity.InterceptionExtension.CustomAttributeMatchingRule には、パラメーター (LogAttribute、ブール値) を受け取るコンストラクターがありません。
container
.AddNewExtension<Interception>()
.Configure<Interception>()
.AddPolicy("MyLoggingPolicy")
.AddMatchingRule<CustomAttributeMatchingRule>(
new InjectionConstructor(typeof(Abstractions.Attributes.LogAttribute), true))
.AddCallHandler<LoggingHandler>(new ContainerControlledLifetimeManager())
.Interception
.Container
.RegisterType<IFirstInterface>(new InjectionFactory((context) => FirstClassFactoryMethod()))
.RegisterType<ISecondInterface>(new InjectionFactory((context) => SecondClassFactoryMethod()));
[AttributeUsage(AttributeTargets.Method)]
public class LogAttribute : Attribute { }
public class LoggingHandler : ICallHandler
{
public int Order { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")} Started: {input.MethodBase.Name}");
var result = getNext()(input, getNext);
Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")} Completed: {input.MethodBase.Name}");
return result;
}
}
スローする行を次のように更新します。
.AddMatchingRule(
new CustomAttributeMatchingRule(typeof(Abstractions.Attributes.LogAttribute), true))
例外がスローされないようにしますが、LoggingHandler は [Log] 属性を持つメソッドからの呼び出しを受け取りません。
注: [Log] でマークされたメソッドは、.Resolve() を使用してインスタンス化されたクラス内の別のアセンブリ内のパブリック メソッドです。