这个问题已经在这里有一个答案:
我有类似下面的代码:
public interface IMyInterface
{
int GetData();
}
public sealed class MyClass : IMyInterface
{
public int GetData() => ...
}
public sealed class MyCachedClass : IMyInterface
{
public MyCachedClass(IMyInterface myInterface, TimeSpan cacheDuration)
{ ... }
public int GetData()
{
int? data = GetDataFromCache();
if (data == null)
{
data = myInterface.GetData();
UpdateCache(data);
}
return data.Value
}
}
现在我可以只是简单的注册使用MyClass的:
container.Register<IMyInterface, MyClass>(Lifestyle.Singleton);
然后我想装饰添加到每个IMyInterface的实例。
container.RegisterDecorator<IMyInterface, MyCachedClass>(...);
不幸的是它不会起作用,因为在构造TimeSpan cacheDuration
参数。我找不到这方面的任何过载。
有没有一种方法是这样的?:
container.RegisterDecorator<IMyInterface>
(instance => new MyCachedClass(instance, TimeSpan.FromMinutes(5));
编辑:标记为复制?另一个问题包含答案,原来配置参数为新的依赖......所以也没有回答我的问题。
该问题主要是,你需要一个值类型注入到装饰的构造。为了解决这个问题,你需要用一个工厂方法,e.g创建服务:
container.Register<IMyInterface>(() =>
{
var decorated = container.GetInstance<MyClass>();
return new MyCachedClass(decorated, TimeSpan.FromMinutes(60));
});
为了获得装饰类,你可以使用容器来解决依赖性。但是,您不能使用IMyInterface
解决装饰服务,因为这将导致循环。虽然这将是更好地使用一个接口,它仍然是代码只是一个地方,你需要改变,如果你想使用其他MyClass
一个类型。