私のプロジェクトにはPageCache
、RavenDBに保存されている次のエンティティがあります。
public class PageCache
{
private readonly IHtmlDocumentHelper htmlDocumentHelper;
public string Id { get; set; }
public string Url { get; set; }
public PageCache(IHtmlDocumentHelper htmlDocumentHelper, string url)
{
this.htmlDocumentHelper = htmlDocumentHelper;
this.Url = url;
}
}
Castle Windsorを使用してIHtmlDocumentHelper
、実行時に実装を注入しています。このメンバーは、PageCache
クラス内で定義されたメソッドで使用されます。簡単にするために、上記のスニペットから削除しました。
PageCache
コンストラクターを使用してオブジェクトを作成すると、すべてが正常に機能します。しかし、コードの他の場所で、PageCache
RavenDBからオブジェクトをロードし直します。
public PageCache GetByUrl(string url)
{
using (var session = documentStore.OpenSession())
{
return session.Query<PageCache>()
.Where(x => x.Url == url)
.FirstOrDefault();
}
}
私の問題は、RavenDBから返されるオブジェクトにhtmlDocumentHelper
メンバーが設定されておらず、PageCache
それに依存するメソッドが使用できなくなっていることです。
つまり、RavenDBに格納されているドキュメントからオブジェクトをロードし直すと、コンストラクターを使用してオブジェクトをビルドしないため、コンストラクターの挿入によってプライベートメンバーが初期化されません。
私はここで何か間違ったことをしていますか?そのような問題をどのように解決しますか?
私は、以下のAyendeによって提案されたソリューションを使用することになりました。コメントで述べた循環依存の問題はDocumentStore
、ウィンザーにを登録したときにのみ発生しましたUsingFactoryMethod()
。DependsOn()
Windsorを使用して、の内部で直接OnCreate()
構成および初期化すると、この問題は奇妙に消えました。DocumentStore
Register()
私のコンテナは現在、次のように初期化されています。
WindsorContainer container = new WindsorContainer();
container.Register(
// Register other classes, such as repositories and services.
// Stripped for the sake of clarity.
// ...
// Register the CustomJsonConverter:
Component.For<CustomJsonConverter>().ImplementedBy<CustomJsonConverter>(),
// The following approach resulted in an exception related to the circular
// dependencies issue:
Component.For<IDocumentStore>().UsingFactoryMethod(() =>
Application.InitializeDatabase(container.Resolve<CustomJsonConverter>()))
// Oddly enough, the following approach worked just fine:
Component.For<IDocumentStore>().ImplementedBy<DocumentStore>()
.DependsOn(new { Url = @"http://localhost:8080" })
.OnCreate(new Action<IDocumentStore>(store =>
store.Conventions.CustomizeJsonSerializer = serializer =>
serializer.Converters.Add(container.Resolve<CustomJsonConverter>())))
.OnCreate(new Action<IDocumentStore>(store =>
store.Initialize()))
.OnDestroy(new Action<IDocumentStore>(store =>
store.Dispose()))
);
正常に動作しているように見えますが、メソッドcontainer.Resolve<CustomJsonConverter>()
内から呼び出さなければならないのは不思議です。container.Register()
これは、依存関係を登録するための合法的なアプローチですか?