【发布时间】: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