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

FMM*_*FMM 5 c# dependency-injection ninject ninject-2

所以,假设我有一个界面IThingFactory:

public interface IThingFactory
{
    Thing GetThing(int thingId);
}
Run Code Online (Sandbox Code Playgroud)

现在,假设我有一个Thing从数据库中检索s 的具体实现.现在,我们还说我有一个具体的实现,它包装了一个现有的,IThingFactory并且Thing在命中包装之前检查是否存在于内存缓存中IThingFactory.就像是:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用依赖注入来处理这样的场景,例如Ninject,以便我可以配置DI容器,以便我可以注入或删除像这样的缓存代理,或者说,执行日志记录的东西,或(在这里插入)?

Pet*_*ete 5

你可以做一些事情:

Bind<IThingFactory> ().To<DefaultThingFactory> ().WhenInjectedInto<CachedThingFactory> ();
Bind<IThingFactory> ().To<CachedThingFactory> ();
Run Code Online (Sandbox Code Playgroud)

这将让消费者不需要指定名称属性,并且仍然相对容易进一步增强.如果您以后想要添加额外的"装饰器"图层以进行日志记录,您可以执行以下操作:

Bind<IThingFactory> ().To<DefaultThingFactory> ().WhenInjectedInto<LoggingThingFactory> ();
Bind<IThingFactory> ().To<LoggingThingFactory> ().WhenInjectedInto<CachedThingFactory> ();
Bind<IThingFactory> ().To<CachedThingFactory> ();
Run Code Online (Sandbox Code Playgroud)

不是最漂亮的,但它的确有效.