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可以这样做吗?如果需要对模型进行一些小修改,只要它们很小,我就会为他们开放。