所以,假设我有一个接口IThingFactory:
So, let's say I have an interface IThingFactory:
public interface IThingFactory { Thing GetThing(int thingId); }现在,假设我有一个具体的实现,可以从数据库中检索Thing.现在,让我们说一个具体的实现,它包装了一个现有的IThingFactory,并在命中被包装的IThingFactory之前在内存中的高速缓存中检查了Thing的存在.像这样:
Now, let's say I have a concrete implementation that retrieves Things from a database. Now, let's also say I have a concrete implementation that wraps an existing IThingFactory and checks for a Thing's presence in, say, an in-memory cache before hitting the wrapped IThingFactory. Something like:
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之类的依赖注入来处理这样的情况,以便我可以配置DI容器,以便可以注入或删除这样的缓存代理,或者说,进行日志记录还是(在此处插入)?
How would I deal with a scenario like this using dependency injection with something like, say, Ninject, so that I could configure the DI container so that I can inject or remove a caching proxy like this, or, say, something that does logging, or (insert here)?
推荐答案您可以执行以下操作:
Bind<IThingFactory> ().To<DefaultThingFactory> ().WhenInjectedInto<CachedThingFactory> (); Bind<IThingFactory> ().To<CachedThingFactory> ();这将使消费者不需要指定name属性,并且仍然相对容易进一步增强.如果您以后想要添加一个额外的装饰器"层来进行日志记录,则可以执行以下操作:
This will let consumers not need to specify a name attribute, and is still relatively easy to further enhance. If you later wanted to add an additional "decorator" layer for logging, you could do:
Bind<IThingFactory> ().To<DefaultThingFactory> ().WhenInjectedInto<LoggingThingFactory> (); Bind<IThingFactory> ().To<LoggingThingFactory> ().WhenInjectedInto<CachedThingFactory> (); Bind<IThingFactory> ().To<CachedThingFactory> ();不是最漂亮的,但它可以工作.
Not the prettiest, but it works.
更多推荐
依赖注入:如何配置用于包装的接口绑定
发布评论