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 は、Unity によって解決せずにプロキシを作成することを提案します。その後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 に答える