依赖注入:如何配置用于包装的接口绑定

编程入门 行业动态 更新时间:2024-10-24 07:25:24
本文介绍了依赖注入:如何配置用于包装的接口绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以,假设我有一个接口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.

更多推荐

依赖注入:如何配置用于包装的接口绑定

本文发布于:2023-11-14 10:23:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586957.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   接口

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!