c# - 依赖注入(inject) : How to configure interface bindings for wrapping

标签 c# dependency-injection ninject ninject-2

那么,假设我有一个接口(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/

相关文章:

c# - PageMethod 未定义错误

c# - .NET C# - WinForm 边框

c# - 哪个 DI 容器会满足这个

java - Guice/DI 和混合注入(inject)和运行时传入的参数

c# - 如何将 Caliburn.Micro.Logging 与 Ninject.Logging & log4net 结合使用

wcf - 服务契约(Contract) WCF 中的 DI

c# - 如何使用 Microsoft.Diagnostics.Runtime 获取有关 StackTrace 中方法的信息?

c# - 序列化为 JSON 时出现 OutOfMemoryException?

java - 是否可以为注入(inject)的 Java 资源设置 Lifestyle

dependency-injection - IoC、AOP 等