首先,如果我对术语的使用是无效的,请尽量纠正但不确定它是否正确,但现在对我来说有点困惑。了解使用基于接口的工厂和普通IoC接口之间的差异instansiation
我正在使用温莎,并无法弄清楚什么时候以及如何(我认为)使用基于接口的工厂实例化,而不是总是正常的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同一对象的方式。为什么我应该使用教学课堂的方式?
这是我是如何配置它
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
做的方式complety方式如果不是,我为什么要用类似于课堂的方式?
(我应该清楚,我读过温莎文档,但没有得到它100%。)
感谢您的时间,我希望这不是模糊。
我想听到的声音是“在大多数其他情况下,不应该用工厂。”,我希望来我就知道我什么时候需要使用的工厂,而不是逼我只是因为它是可以使用它们;) – Andreas 2014-10-29 20:31:02