2
就拿這個簡單的例子:實現少打字工廠發出
class Program
{
static void Main(string[] args)
{
var windsorContainer = new WindsorContainer();
windsorContainer.Install(new WindsorInstaller());
var editor = windsorContainer.Resolve<IEditor>();
editor.DoSomething();
Console.ReadKey();
}
}
public class WindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<ISomeOtherDependency>().ImplementedBy<SomeOtherDependency>());
container.Register(Component.For<IReviewingService>().ImplementedBy<ReviewingService>());
container.Register(Component.For<IEditor>().ImplementedBy<Editor>());
container.Register(Component.For<Func<IReviewingServiceFactory>>().AsFactory());
}
}
public interface IEditor
{
void DoSomething();
}
public class Editor : IEditor
{
private readonly Func<IReviewingServiceFactory> _reviewingService;
public Editor(Func<IReviewingServiceFactory> reviewingService)
{
_reviewingService = reviewingService;
}
public void DoSomething()
{
var rs = _reviewingService();
var reviews = new List<string> {"Review #1", "Review #2"};
var reviewingService = rs.Create(reviews);
reviewingService.Review();
}
}
public interface IReviewingServiceFactory
{
IReviewingService Create(IList<string> reviews);
}
public interface IReviewingService
{
void Review();
}
public class ReviewingService : IReviewingService
{
private readonly IList<string> _reviews;
private readonly ISomeOtherDependency _someOtherDependency;
public ReviewingService(IList<string> reviews, ISomeOtherDependency someOtherDependency)
{
_reviews = reviews;
_someOtherDependency = someOtherDependency;
}
public void Review()
{
Console.WriteLine("Reviewing...");
}
}
public interface ISomeOtherDependency
{
}
public class SomeOtherDependency : ISomeOtherDependency
{
}
有了這個例子我希望控制檯輸出「回顧......」。然而,溫莎拋出異常:
No component for supporting the service CastleWindsorTypedFactor.IReviewingServiceFactory was found
我的溫莎安裝程序有什麼問題?
啊。我的印象是,如果我的構造函數參數是'Func',那麼我必須註冊'Func '而不僅僅是'T'。我只修改了我在Windsor註冊的內容,而不是從我的構造函數參數中的'Func ',因爲我希望它被延遲加載。謝謝。 –
User
如果你想讓你的編輯器注入'Func',那麼是的 - 你需要註冊'Func'。但是,當你只需要注入一個IReviewingServiceFactory時,你完全沒有理由要花費額外的步驟來調用'Func'來獲取工廠。 –
mookid8000
這很有道理。感謝您更新您的答案。 – User