【发布时间】:2014-10-26 22:16:36
【问题描述】:
首先,如果我使用的术语无效,我很抱歉,我试图让它正确但不确定是否正确,这让我现在有点困惑。
我正在使用 Windsor,但无法确定何时以及如何(我认为)使用基于接口的工厂实例化,而不是通常的 ctor(IObj obj)。
让我举个例子。我有这个构造函数
private ICache _cache;
private ICache _cache2;
public HomeController(ICacheFactory cacheFactory, ICache cache)
{
this._cache = cacheFactory.Create<ICacheFactory>();
this._cache2 = cache;
}
我设置代码的方式,_cache 和 _cache2 返回 exakt 相同的对象。为什么我应该使用 ICacheFactory 实例化类的方式?
这就是我的配置方式
public interface ICacheFactory
{
ICache Create<T>();
}
public interface ICache
{
bool Get<T>(string key, out T exists);
}
public bool Get<T>(string key, out T result)
{
// my code
}
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Classes.FromThisAssembly().BasedOn<IController>().LifestyleTransient());
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<ICacheFactory>().AsFactory());
container.Register(Component.For<ICache>().ImplementedBy<CacheFactory>().LifestyleTransient());
}
我在想 CacheFactory 就像我做的时候一样
public class CacheFactory : ICache
{
private static ICache cacheObject;
public static ICache Current
{
get
{
if (cacheObject == null)
cacheObject = new CacheFactory();
return cacheObject;
}
}
public bool Get<T>(string key, out T result)
{
// my code
}
}
那么,我对 interface-based factories 做什么的思考方式是否完整?如果不是,我为什么要使用 ICacheFactory 实例化类的方式?
(我应该清楚,我已经阅读了 Windsor 文档,但没有 100% 理解。)
感谢您的宝贵时间,我希望它不会模糊。
【问题讨论】:
标签: .net inversion-of-control castle-windsor factory-pattern windsor-facilities