I'm using Unity 2.0 in my project where I'm reading a lot of files at the same time inside Parallel.ForEach block of code:
Parallel.ForEach(files, currentFile =>
{
using(IMsBuildProjectLoader msBuildProject = Container.Resolve<IMsBuildProjectLoader>(new ParameterOverride("projectFileName", currentFile)))
{
// file processing
}
}
Resolve(new ParameterOverride("projectFileName", currentFile) function sometimes throw 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'
This is when the same file is loaded at the same time - Resolve function is creating two IMsBuildProjectLoader instances with the same parameter at the same time. It cannot be solved by files.Distinct() filter. Above code is only a code example to explain my problem.
The question is: How to implement thread safe UnityContainer.Resolve function? Is it possible to do it using some Unity extension class?
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 is registered this way:
container.RegisterType<IMsBuildProjectLoader, MsBuildProjectLoader>();