我使用Bojan Resnik在this question中描述的方法來解析未在Windsor容器中註冊的類的實例。問題是我不希望這些類作爲「服務」提供給其他已解決的實例。Castle IoC - 如何防止註冊組件被解析爲依賴關係?
例如,給出以下類:
class Order
{
public Order(ITaxCalculator tc)
{
// ...
}
}
class SomeOtherThing
{
public SomeOtherThing(ISomeOtherService sos)
{
// ...
}
Order CurrentOrder
{
get;
set;
}
}
static class WindsorExtensions
{
public static object Create(this IWindsorContainer container, Type type)
{
if (!type.IsClass)
{
throw new ArgumentException("not class", "type");
}
if (!container.Kernel.HasComponent(type))
{
container.Kernel.AddComponent(type.FullName, type, LifestyleType.Transient);
}
return container.Resolve(type);
}
public static T Create<T>(this IWindsorContainer container)
{
return (T)ResolveType(container, typeof(T));
}
}
我希望能夠說:
Order order = container.Create<Order>();
SomeOtherThing thing = container.Create<SomeOtherThing>();
但我不想訂購的新實例獲得注入到SomeOtherThing的CurrentOrder屬性。基本上,我希望容器創建實例,以便可以注入依賴關係,但我不希望這些類可用於注入其他類。
爲了達到這個目標,我不介意爲容器寫額外的擴展名,只要有人能指出我正確的方向。