0

我有一个应用程序,它有一个基类和派生类,每个实现类都有自己的接口。我想使用 Unity 的拦截对基类的派生类型进行异常处理。

我是拦截新手,所以我不知道所有的怪癖。据我所知,我必须在每个实现解析中注册拦截。关键是我所有的实现都有一个基类,所以我认为我可以跳过冗余并仅在基类上设置拦截,这将在每个实现类上触发。

这是我的设置:

public class NotificationViewModel
{
   // some properties
}

public class CompanyViewModel : NotificationViewmodel
{
   // some properties
}

public class BaseService
{
}

public interface ICompanyService
{
   public NotificationViewModel Test();
}

public class CompanyService : BaseService, ICompanyService
{
   public CompanyViewModel Test()
   {
      // call exception
   }
}

public class TestUnityContainer : UnityContainer
{
   public IUnityContainer RegisterComponents()
   {
      this
         .AddNewExtension<Interception>()
         .RegisterType<ICompanyService, CompanyService>(
            new Interceptor<InterfaceInterceptor>(),
            new InterceptionBehavior<TestInterceptionBehavior>());

      return this;
    }
}

public class TestInterceptionBehavior : IInterceptionBehavior
{
   public IEnumerable<Type> GetRequiredInterfaces()
   {
      return new[] { typeof( INotifyPropertyChanged ) };
   }

   public IMethodReturn Invoke( IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext )
   {
      IMethodReturn result = getNext()( input, getNext );

      if( result.Exception != null && result.Exception is TestException )
      {             
         object obj = Activator.CreateInstance( ( ( System.Reflection.MethodInfo )input.MethodBase ).ReturnType );
         NotificationViewModel not = ( NotificationViewModel )obj;
         // do something with view model
         result.ReturnValue = obj;
         result.Exception = null;
      }

      return result;
   }

   public bool WillExecute
   {
      get { return true; }
   }
}

这工作正常,但我想有这样的东西TestUnityContainer

public class TestUnityContainer : UnityContainer
{
   public IUnityContainer RegisterComponents()
   {
      this
         .AddNewExtension<Interception>()
         .RegisterType<BaseService>(
            new Interceptor<InterfaceInterceptor>(),
            new InterceptionBehavior<TestInterceptionBehavior>() );
         .RegisterType<ICompanyService, CompanyService>();

      return this;
    }
}

我将有更多从基础服务继承的服务类,我认为这会为我节省很多时间,因为它们都有相同的拦截行为。

这在 Unity 中是否可行?如何实现?如果需要对模型进行一些小的修正,我愿意接受,只要它们是次要的。

4

1 回答 1

0

我建议您查看 Unity 中的策略注入,而不是手动对类型应用行为。有了政策,您必须:-

  1. 创建一个实现 ICallHandler 的类(基本上是简化的 IInterceptionBehavior)——这将是您的异常处理程序行为。
  2. 创建一个具有“匹配规则”的策略 - 在您的情况下,一个将您的 CallHandler 用于实现 BaseService 或类似的任何注册类型的策略。
  3. 您仍然需要将所有服务注册到 Unity 中,但现在传入 Interceptor 和 InterceptionBehavior。如果你有很多服务,我建议你看看我的Unity Automapper 之类的东西,它可以简化注册和处理拦截行为。
于 2013-04-30T21:25:13.900 回答