【问题标题】:UNITY: How to implement thread safe Container.Resolve() function with constructor injection?UNITY:如何使用构造函数注入实现线程安全的 Container.Resolve() 函数?
【发布时间】:2014-12-21 23:12:40
【问题描述】:

我在我的项目中使用 Unity 2.0,我在 Parallel.ForEach 代码块中同时读取大量文件:

Parallel.ForEach(files, currentFile =>
{
    using(IMsBuildProjectLoader msBuildProject = Container.Resolve<IMsBuildProjectLoader>(new ParameterOverride("projectFileName", currentFile)))
    {
        // file processing
    }
}

Resolve(new ParameterOverride("projectFileName", currentFile) 函数有时会抛出 ResolutionFailedException:

ResolutionFailedException: Resolution of the dependency failed, 
type = "Porthus.Build.Common.Interfaces.IMsBuildProjectLoader", name = "(none)". 
Exception occurred while: Calling constructor XXX.Build.Common.Types.MsBuildProjectLoader(System.String projectFileName). 
Exception is: ArgumentException - Item has already been added. Key in dictionary: 'xxx'  Key being added: 'xxx'

这是同时加载同一个文件时 - Resolve 函数正在同时创建两个具有相同参数的 IMsBuildProjectLoader 实例。它无法通过 files.Distinct() 过滤器解决。上面的代码只是解释我的问题的代码示例。

问题是:如何实现线程安全的UnityContainer.Resolve函数?是否可以使用一些 Unity 扩展类来做到这一点?

IMsBuildProjectLoader

public interface IMsBuildProjectLoader : IDisposable
{
}

MsBuildProjectLoader

public class MsBuildProjectLoader : Project, IMsBuildProjectLoader
{
    public MsBuildProjectLoader(string projectFileName)
        : base()
    {
        // Load the contents of the specified project file.
        Load(projectFileName);
    }
}

MsBuildProjectLoader 是这样注册的:

container.RegisterType<IMsBuildProjectLoader, MsBuildProjectLoader>();

【问题讨论】:

  • 这并不能直接回答您的问题,但我认为您可能做错了。您的类应该被注入一个 IMsBuildProjectLoader,并且在您的循环中,您应该在 IMsBuildProjectLoader 上调用一个将文件名作为参数的方法。然后应该将线程安全纳入您的 IMsBuildProjectLoader 实现中。我的 0.02 美元。
  • 是的,这是另一种选择。谢谢

标签: c# unity-container constructor-injection


【解决方案1】:

Resolve 实际上是线程安全的(或者微软 P&P 的人这么说)。 MsBuildProjectLoader 的实现可能不是线程安全的,或者更具体地说,它是构造函数。 通过以相同的异步方式使用 new 创建 MsBuildProjectLoader 的新实例,您可能会遇到同样的问题

您没有包括 Load 的实现,但根据例外情况,我假设它以非线程安全的方式操作共享或静态字典。 如果是这种情况,您应该使该字典线程安全(例如,将其替换为 ConcurrentDictionary)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    相关资源
    最近更新 更多