3

ここでの回答で説明されている動作を取得したいと思いますが、コードを使用して構成を使用します。コード サンプルは、単一性に関連するものなしで作成され、構成を通じて動作を追加するカスタム属性を示しています。

カスタム属性は、同じソリューションで参照される別のアセンブリにあります。

問題は、構成中に例外がスローされることです。

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() を使用してインスタンス化されたクラス内の別のアセンブリ内のパブリック メソッドです。

4

2 に答える 2

5

同じ問題に遭遇した人のために-登録された型でインターセプト動作を定義する必要がありました:

.RegisterType<IFirstInterface>(
    new InjectionFactory((context) => FirstClassFactoryMethod())
    new Interceptor<TransparentProxyInterceptor>()
    new InterceptionBehavior<PolicyInjectionBehavior>())
.RegisterType<ISecondInterface>(
    new InjectionFactory((context) => SecondClassFactoryMethod())
    new Interceptor<TransparentProxyInterceptor>()
    new InterceptionBehavior<PolicyInjectionBehavior>()));
于 2017-09-24T21:41:06.557 に答える
0

同じエラーが発生し、Filip ソリューションを試しましたが、うまくいきませんでした。私は、InjectionFactory (Unity 4.0.1) の InjectionConstructor を変更しました。

container
.AddNewExtension<Interception>()
.Configure<Interception>()
    .AddPolicy("MyLoggingPolicy")
    .AddMatchingRule<CustomAttributeMatchingRule>(
    new InjectionFactory((context) => new CustomAttributeMatchingRule(typeof(Abstractions.Attributes.LogAttribute), true))
    .AddCallHandler<LoggingHandler>(new ContainerControlledLifetimeManager());

これが誰かに役立つことを願っています。

于 2019-03-02T10:35:55.983 に答える