如何在温莎城堡中使用接口的嵌套实现?
假设我有一个用于获取数据的接口及其实现:
interface IResourceProvider
{
string Get( Uri uri );
}
class HttpResourceProvider : IResourceProvider
{
public string Get( Uri uri )
{
// Download via HTTP.
}
}
我可以在温莎城堡中注册它,如下所示:(
container.Register
( Component.For<IResourceProvider>().ImplementedBy<HttpResourceProvider>()
);
这一切都很好)。
如果我随后决定想要一个缓存实现,如下所示:
class CachingResourceProvider : IResourceProvider
{
public CachingResourceProvider( IResourceProvider resourceProvider )
{
_resourceProvider = resourceProvider;
}
public string Get( Uri uri )
{
// Return from cache if it exists.
// Otherwise use _resourceProvider and add to cache.
}
private readonly IResourceProvider _resourceProvider;
}
如何注册这些嵌套依赖项?,即,我想说 IResourceProvider
是由 CachingResourceProvider 实现的
,除了构造函数中的 HttpResourceProvider
。
Suppose I have an interface for fetching data, and an implementation of it:
interface IResourceProvider
{
string Get( Uri uri );
}
class HttpResourceProvider : IResourceProvider
{
public string Get( Uri uri )
{
// Download via HTTP.
}
}
I can register this in Castle Windsor as follows:
container.Register
( Component.For<IResourceProvider>().ImplementedBy<HttpResourceProvider>()
);
(Which is all fine).
If I then decided I wanted a caching implementation as follows:
class CachingResourceProvider : IResourceProvider
{
public CachingResourceProvider( IResourceProvider resourceProvider )
{
_resourceProvider = resourceProvider;
}
public string Get( Uri uri )
{
// Return from cache if it exists.
// Otherwise use _resourceProvider and add to cache.
}
private readonly IResourceProvider _resourceProvider;
}
How would I register these nested dependencies? i.e., I want to say an IResourceProvider
is implemented by a CachingResourceProvider
, except where in the constructor, where it's a HttpResourceProvider
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需在
HttpResourceProvider
之前注册CachingResourceProvider
- 例如顺便说一句 - 这被称为 装饰器设计模式。
Just register
CachingResourceProvider
beforeHttpResourceProvider
- e.g.BTW - this is know as the Decorator design pattern.
这称为装饰器模式...
请参阅此链接作为示例:http://mikehadlow.blogspot.com/2010/01/10-advanced-windsor-tricks-4-how-to.html
This is known as the Decorator Pattern...
See this link as an example: http://mikehadlow.blogspot.com/2010/01/10-advanced-windsor-tricks-4-how-to.html