Dependency injection RavenDB与构造函数注入
在我的项目中,我有以下Dependency injection RavenDB与构造函数注入,dependency-injection,ravendb,constructor-injection,Dependency Injection,Ravendb,Constructor Injection,在我的项目中,我有以下PageCache实体,它存储在RavenDB中: public class PageCache { private readonly IHtmlDocumentHelper htmlDocumentHelper; public string Id { get; set; } public string Url { get; set; } public PageCache(IHtmlDocumentHelper htmlDocumentH
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
对象时,一切正常。但在代码的其他地方,我从RavenDB加载PageCache
对象:
public PageCache GetByUrl(string url)
{
using (var session = documentStore.OpenSession())
{
return session.Query<PageCache>()
.Where(x => x.Url == url)
.FirstOrDefault();
}
}
虽然它似乎工作得很好,但我觉得从container.Register()方法内部调用container.Resolve()
很奇怪
这是注册依赖项的合法方法吗?Christian,
我们不能用你的ctor,我们不知道放什么进去
相反,您可以使用此技术告诉RavenDB如何创建对象:
然后,您可以使用documentStore.Conventison.CustomizeSerializer将此连接到中谢谢您的支持,Ayende。我现在遇到的问题是,这个CustomSerializer将依赖于HtmlDocumentHelper实现(因此它可以将其传递到PageCache构造函数)。但是HtmlDocumentHelper目前依赖于PageCacheRepository,而PageCacheRepository本身依赖于DocumentStore来在数据库中持久化。由于DocumentStore现在依赖于此CustomSerializer,因此我们创建了Windsor无法解析的循环依赖项。换句话说,我们现在有以下依赖项:HtmlDocumentHelper->PageCacheRepository->DocumentStore->CustomSerializer->HtmlDocumentHelper.@Ayende该选项是否要求模型在链接引用中具有公共设置器?你们不能做一些类似MongoDB 2 C驱动程序对其BSON构造函数所做的事情吗?它按名称将构造函数参数映射到只读属性,这样您就可以在类Foo{[bsonstructor]public Foo(Bar-MyBar){this.Bar=Bar;}[bsonement]public Bar-MyBar{get;}}
中拥有真正不可变的对象。事实上,这一直是让我留在MongoDB的主要原因。
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()))
);