我使用Unity 2.0在我的项目中,我读了很多文件在代码Parallel.ForEach块内的同一时间:UNITY:如何使用构造函数注入实现线程安全的Container.Resolve()函数?
Parallel.ForEach(files, currentFile =>
{
using(IMsBuildProjectLoader msBuildProject = Container.Resolve<IMsBuildProjectLoader>(new ParameterOverride("projectFileName", currentFile)))
{
// file processing
}
}
解析(新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'
这是当同一文件在同一时间下载 - 解决功能与在同一时间同一参数创建两个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。 – BFree 2012-02-07 16:33:18
是的,那是另一种选择。谢谢 – Ludwo 2012-02-07 19:54:33