将构造函数参数传递给OutputCacheProvider

时间:2012-08-16 09:37:05

标签: asp.net-mvc web-config ninject

我已经实现了自定义OutputCacheProvider

public class MongoDBCacheProvider : OutputCacheProvider, IDisposable { ... }

cacheprovider的注册方式如下:

<outputCache defaultProvider="MongoDBCacheProvider" enableOutputCache="true"  >
  <providers>
    <add name="MongoDBCacheProvider" type="Mynamespace.Core.Caching.MongoDBCacheProvider, Mynamespace.Core" />
  </providers>
</outputCache>

我需要将一些参数传递给构造函数。我想使用Ninject绑定我的缓存提供程序。

this.Bind<System.Web.Caching.OutputCacheProvider>()
    .To<Core.Caching.MongoDBCacheProvider>()
    .WithConstructorArgument("databaseName", dbName);

必须传递更多参数,但这只是一个例子。我确信存在简单的解决方案,以某种方式获得该字符串,但我更喜欢使用Ninject,就像我用于所有其他类。

这失败并显示消息:“没有为此对象定义无参数构造函数。”以下绑定也不起作用。

this.Bind<Core.Caching.MongoDBCacheProvider>().ToSelf()
    .InSingletonScope()
    .WithConstructorArgument("databaseName", dbName);

我已经验证绑定在错误发生之前运行。 ASP .NET以某种方式绕过了ninject绑定。 似乎没有任何方法可以插入工厂。

有人知道如何将构造函数参数传递给派生的OutputCacheProvider吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以通过在应用启动期间注入对象,在网络应用生命周期的早期Inject进入对象。

注意,您必须优先使用Property Setter Injection而不是构造函数注入,因为很可能无法让缓存提供程序提供程序来控制实例创建。

请参阅this blog post by @Remo Gloor

相关问题