用于非通用接口的简单注入器装饰器

时间:2015-06-03 19:37:01

标签: decorator simple-injector

我尝试了以下但不起作用(ActivationException)。

public interface IOp { object Execute(object value); }

public class SimpleOp : IOp { public object Execute(object value) { return value; } }

public class CompressOp : IOp {
    private readonly IOp nextOp;
    public CompressOp(IOp nextOp) { this.nextOp = nextOp; }
    public object Execute(object value)
    {
        return this.Compress(this.nextOp.Execute(value));
    }
}

var container = new Container();
container.RegisterAll<IOp>(typeof(SimpleOp), typeof(CompressOp));
Container.RegisterDecorator(typeof(IOp), typeof(CompressOp));
var op = container.GetInstance<IOp>(); <-- ActivationException

IOp界面确实不需要是通用类型,因为它设计用于对任何对象进行相同的处理。我是否必须强制它成为泛型,然后始终使用object作为类型参数,这样我才能使用装饰器模式?

1 个答案:

答案 0 :(得分:3)

试试这个

var container = new Container();
container.Register<IOp, SimpleOp>();
Container.RegisterDecorator(typeof(IOp), typeof(CompressOp));
var op = container.GetInstance<IOp>();