2013-04-21 98 views
0

我有一个应用程序,它有一个基类和从它的派生类,每个实现类有自己的接口。我想使用Unity的拦截来处理派生类型的基类的异常处理。Microsoft 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可以这样做吗?如果需要对模型进行一些小修改,只要它们很小,我就会为他们开放。

回答

0

我建议你看一下Unity中的Policy Injection,而不是手动在类型上应用行为。有了这些策略,您必须: -

  1. 创建一个实现ICallHandler的类(基本上是一个简化的IInterceptionBehavior) - 这将是您的异常处理程序行为。
  2. 创建一个具有“匹配规则”的策略 - 对于您的情况,使用CallHandler对任何实现BaseService或类似的注册类型的策略。
  3. 您仍然需要将所有服务注册到Unity,但现在传入Interceptor和InterceptionBehavior。如果你有很多服务,我会建议看看像我的Unity Automapper这将简化注册和不必拦截拦截行为。