gpt4 book ai didi

dependency-injection - RavenDB 和构造函数注入(inject)

转载 作者:行者123 更新时间:2023-12-04 08:22:23 27 4
gpt4 key购买 nike

在我的项目中,我有以下 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 注入(inject) 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 中的文档中加载对象时,它不会使用我的构造函数来构建对象,因此不会通过构造函数注入(inject)来初始化私有(private)成员。

我在这里做错了吗?你会如何解决这样的问题?

我最终使用了下面 Ayende 提出的解决方案。我在评论中提到的循环依赖问题仅在我注册 DocumentStore 时出现。在温莎与 UsingFactoryMethod() .当我使用 Windsor 的 DependsOn() 时,这个问题奇怪地消失了。和 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() 内部方法。

这是注册依赖项的合法方法吗?

最佳答案

基督教,
我们不能使用你的 ctor,我们不知道在里面放什么。

相反,您可以使用此技术告诉 RavenDB 如何创建对象:
http://james.newtonking.com/projects/json/help/CustomCreationConverter.html

然后你可以使用 documentStore.Conventison.CustomizeSerializer 连接它

关于dependency-injection - RavenDB 和构造函数注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10662388/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com