1

对于我的单元测试,我目前正在使用 Moq 模拟我的拦截器和拦截的类,然后在 Unity 中注册拦截的实例并为接口设置默认拦截器。然后我解析实例并调用拦截的方法,并验证正在调用拦截方法。

_mockInterceptor = new Mock<ExternalInterceptor>().As<IInterceptRelay>();
_mockInterception = new Mock<TestInterception> { CallBase = true }.As<IInterceptRelay>();

Container.RegisterInstance(_mockInterception.Object as ITestInterception);
UnityContainer.Configure<Interception>().SetDefaultInterceptorFor<ITestInterception>(new InterfaceInterceptor());

var test = Container.Resolve<ITestInterception>();
var returnValue = test.TestTheExternalInterception(TestMessage);

_mockInterceptor.Verify(i => i.ExecuteAfter(It.IsAny<object>(), It.IsAny<IEnumerable>(), It.IsAny<LoggingInterceptionAttribute>(), It.IsAny<IMethodResult>()), Times.Once());

这很好用,但是我宁愿在注册期间设置拦截,就像我在注册服务/单例时一样,以保持一切一致。

// Typical registration
UnityContainer.RegisterType<TFrom, TTo>(new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<PolicyInjectionBehavior>());
// Singleton registration
UnityContainer.RegisterType<TFrom, TTo>(new ContainerControlledLifetimeManager(), new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<PolicyInjectionBehavior>());

我看不到任何使用该方法配置拦截的IUnityContainer.RegisterInstance()方法,因为它不需要任何InjectionMembers. 如果我UnityContainer.Configure<Interception>().SetDefaultInterceptorFor<T>()在解析之前调用,我实际上可以对实例使用拦截。

是否有更好/更简单的方法来注册或模拟拦截器?

4

1 回答 1

6

Unity Interception 提供创建代理而不通过统一解决它们。然后,您可以RegisterInstance自己创建的对象。

有关更多信息,请参阅Unity 的依赖注入第 77 页“没有 Unity 容器的拦截”。

我从这里举了下面的例子:

ITenantStore tenantStore = Intercept.ThroughProxy<ITenantStore>(
    new TenantStore(tenantContainer, blobContainer),
    new InterfaceInterceptor(),
    new IInterceptionBehavior[]
    {
        new LoggingInterceptionBehavior(),
        new CachingInterceptionBehavior()
    });
于 2014-10-07T11:23:17.333 回答