那么,假设我有一个接口(interface) IThingFactory
:
public interface IThingFactory
{
Thing GetThing(int thingId);
}
现在,假设我有一个从数据库中检索 Thing
的具体实现。现在,我们还假设我有一个具体的实现,它包装了一个现有的 IThingFactory
并在命中包装之前检查一个 Thing
是否存在于内存缓存中ITingFactory
。像这样的东西:
public class CachedThingFactory : IThingFactory
{
private IThingFactory _wrapped;
private Dictionary<int, Thing> _cachedThings;
public CachedThingFactory(IThingFactory wrapped)
{
this._wrapped = wrapped;
_cachedThings = new Dictionary<int,Thing>();
}
public Thing GetThing(int thingId)
{
Thing x;
if(_cachedThings.TryGetValue(thingId, out x))
return x;
x = _wrapped.GetThing(thingId);
_cachedThings[thingId] = x;
return x;
}
}
我将如何使用诸如 Ninject 之类的依赖项注入(inject)来处理这样的场景,以便我可以配置 DI 容器,以便我可以注入(inject)或删除这样的缓存代理,或者说,是记录还是(在此处插入)?
最佳答案
您可以按照以下方式做一些事情:
Bind<IThingFactory> ().To<DefaultThingFactory> ().WhenInjectedInto<CachedThingFactory> ();
Bind<IThingFactory> ().To<CachedThingFactory> ();
这会让消费者不需要指定name属性,而且还是比较容易进一步提升的。如果您稍后想为日志添加一个额外的“装饰器”层,您可以这样做:
Bind<IThingFactory> ().To<DefaultThingFactory> ().WhenInjectedInto<LoggingThingFactory> ();
Bind<IThingFactory> ().To<LoggingThingFactory> ().WhenInjectedInto<CachedThingFactory> ();
Bind<IThingFactory> ().To<CachedThingFactory> ();
不是最漂亮的,但它确实有效。
关于c# - 依赖注入(inject) : How to configure interface bindings for wrapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6752674/