public virtual IDataContext Register([NotNull] UnitOfWorkConfig config)
{
DataSource dataSource;
if (!dataSourcesProvider().TryGetValue(config.SourceName, out dataSource))
{
if (config.SourceName == string.Empty)
{
throw new Exception("Default data source is not registered.");
}
throw new Exception(string.Format("Data source with name '{0}' is not registered.", config.SourceName));
}
config = new UnitOfWorkConfig(
config.SourceName,
config.IsolationLevel == IsolationLevel.Unspecified ? dataSource.DefaultIsolationLevel : config.IsolationLevel,
config.Require);
if (config.Require == Require.New)
{
return new DataContextDecorator(
new DataContext(config, new Lazy<IDataSession>(() => dataSource.BuildSession(config.IsolationLevel), false), terminationPolicy),
contexts);
}
// ReSharper disable once ImplicitlyCapturedClosure
var context = (from ctx in contexts where ctx.WrappedContext.Configuration.SourceName == config.SourceName select ctx).LastOrDefault();
if (context != null)
{
if (!context.WrappedContext.Configuration.IsolationLevel.IsCompatible(config.IsolationLevel))
{
throw new Exception(
string.Format("Isolation level '{0}' is not compatible with '{1}'.", context.WrappedContext.Configuration.IsolationLevel, config.IsolationLevel));
}
return new DataContext.Subordinate(context.WrappedContext);
}
if (config.Require == Require.Existing)
{
throw new Exception("Unit of work requires existing unit of work at the top level, but nothing has been found.");
}
context = new DataContextDecorator(
new DataContext(config, new Lazy<IDataSession>(() => dataSource.BuildSession(config.IsolationLevel), false), terminationPolicy),
contexts);
return context;
}