As Vahid N.'s answer may be useful in discussion :
My version, produces a lazy loaded thread safe singleton, but your Initialize
method is not thread safe. Try:
public static class StructureMapObjectFactory
{
private static readonly Lazy<Container> _containerBuilder = new Lazy<Container>(() => new Container(), LazyThreadSafetyMode.ExecutionAndPublication);
public static IContainer Container
{
get { return _containerBuilder.Value; }
}
public static void Initialize<T>() where T : Registry, new()
{
Container.Configure(x =>
{
x.AddRegistry<T>();
});
}
}
And how to use :
DbContext dataContext = StructureMapObjectFactory.Container.TryGetInstance<DbContext>();