依赖注入:如何配置用于包装的接口绑定 [英] Dependency Injection: How to configure interface bindings for wrapping

查看:76
本文介绍了依赖注入:如何配置用于包装的接口绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于依赖注入:如何配置用于包装的接口绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆