gpt4 book ai didi

dependency-injection - 配置文件中映射正确时的 Unity Container ResolutionFailedException

转载 作者:行者123 更新时间:2023-12-04 08:21:54 25 4
gpt4 key购买 nike

我使用的是 ServiceLocator我正在使用 Unity

public ServiceLocator(IUserStore userStore, IProdcutsStore productsStore, ...etc) {}

public IUserStore UserStore
{
get { return userStore; }
}

这一切都很好,但我想要存储库的惰性实例化,因为它们的使用非常少。

所以我的 ServiceLocator现在看起来像
    public ServiceLocator(IUnityContainer container) {}

public IUserStore UserStore
{
get { return (IUserStore)container.Resolve(typeof(IUserStore)); }
}

// ...etc

我现在收到一个非常无用的 ResolutionFailedException 错误

Resolution of the dependency failed, type = "DomainModel.DataServices.Interface.IUserStore", name = "". Exception message is: The current build operation (build key Build Key[DomainModel.DataServices.Interface.IUserStore, null]) failed: The current type, DomainModel.DataServices.Interface.IUserStore, is an interface and cannot be constructed. Are you missing a type mapping? (Strategy type BuildPlanStrategy, index 3)



告诉我我的接口(interface)类型不能被实例化,因为它是一个接口(interface)是毫无意义的。我知道这是一个接口(interface),这就是为什么容器应该为我解决它!

无论如何,这里要注意的一点是,我知道配置中的类型映射很好,因为当我直接注入(inject)类型接口(interface)而不是尝试延迟加载时,它可以毫无问题地解决它。

我错过了什么,这意味着某些地方必须改变才能以这种方式延迟加载?

更新:我猜这里发生了什么,当我将容器 DI 到 ServiceLocator 中时,“主”容器每次都实例化一个新容器,然后没有正确配置。我想也许我需要一些方法来指定我要通过 this in 作为容器,而不是用新的实例化来解决它。

最佳答案

你的方向有点错误......起初你有一个可测试的类,它在构造函数中声明了它的依赖项,然后你把它变成了不可测试的,在容器内要求“一些东西”......不好=(

您应该为昂贵的对象实现一些工厂接口(interface)并在构造函数中使用它,或者(如果可以)切换到 Unity 2.0 并使用 Automatic Factories :

public ServiceLocator(Func<IUserStore> userStoreBuilder)

//...

public IUserStore UserStore
{
get { return userStoreBuilder(); }
}

如果您只想创建该对象的实例一次,您可以将 cahcing 添加到该属性,或者使用 .NET 4.0 您可以尝试 asking Lazy in the constructor .

附言哦是的。并回答您的特殊问题 =) 如果您仍想在其他地方注入(inject)容器实例,则需要先在其内部注册它 =)
container.RegisterInstance<IUnityContainer>(container);

修复(见评论)不要在自身内部注册 Unity 容器,这将导致 container.Dispose() 中的 StackOverflowException ,正确的实例将作为依赖注入(inject)而无需注册。

关于dependency-injection - 配置文件中映射正确时的 Unity Container ResolutionFailedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3701020/

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