For my Unit Tests I am currently mocking my interceptor and intercepted classes using Moq, then registering the intercepted instance in Unity and setting the default interceptor for the interface. I then resolve the instance and call methods on the intercepted and verify that the interception method is being called.
_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());
This works great, however I would rather set the interception during registration like I do when I register a service/singleton to keep everything consistent.
// 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>());
I cannot see any way to configure interception using the IUnityContainer.RegisterInstance()
method as it doesn't take any InjectionMembers
. I can actually use interception with an instance if I call UnityContainer.Configure<Interception>().SetDefaultInterceptorFor<T>()
before resolving.
Is there a better/easier way of registering or mocking an interceptor?
Unity Interception offers to create proxies without resolving them by unity. You can then RegisterInstance
the object you've created yourself.
For more infromation see Dependency Injection with Unity page 77 "Interception Without the Unity Container".
I took the following example from here:
ITenantStore tenantStore = Intercept.ThroughProxy<ITenantStore>(
new TenantStore(tenantContainer, blobContainer),
new InterfaceInterceptor(),
new IInterceptionBehavior[]
{
new LoggingInterceptionBehavior(),
new CachingInterceptionBehavior()
});