0

我想装饰从特定接口派生的所有创建的实例。

public interface IInterface
{
    void Execute(); //// only this shall be intercepted
}

public interface IDerivedInterface : IInterface
{
    bool CanExecute { get; } //// this shall not be intercepted
}

public class DirectImplementation : IInterface
{
    public void Execute()
    {
    }
}

public class DerivedImplementation : IDerivedInterface
{
    public void Execute()
    {
    }

    public bool CanExecute { get; }
}

public class Decorator : IInterface
{
    public Decorator(IInterface inner)
    {
        Inner = inner;
    }

    public IInterface Inner { get; }

    public void Execute()
    {
        Console.WriteLine("Something is executed");
        Inner.Execute();
    }
}

我的期望在这个单元测试中实现

[Test]
public void Should_know_how_structure_map_works()
{
    var container = new Container(
        c =>
        {
            c.For<IInterface>().Use<DirectImplementation>();
            c.For<IDerivedInterface>().Use<DerivedImplementation>();

            c.For<IInterface>().DecorateAllWith<Decorator>();
        });

    var interfaceImpl = container.GetInstance<IInterface>();
    var derivedInterfaceImpl = container.GetInstance<IDerivedInterface>();

    Assert.That(interfaceImpl, Is.TypeOf<Decorator>());
    Assert.That(((Decorator)interfaceImpl).Inner, Is.TypeOf<DirectImplementation>());

    Assert.That(derivedInterfaceImpl, Is.TypeOf<Decorator>());
    Assert.That(((Decorator)derivedInterfaceImpl).Inner, Is.TypeOf<DerivedImplementation>());
}

但这显然不能完全填充,因为Decorator没有实现IDerivedInterface. 所以我的问题是: 有什么方法可以以这样的方式配置 StructureMap,我可以拦截对 IInterface.Execute 的所有调用?

4

0 回答 0