Example #1
0
        protected MongoDbContext(MongoDbContextOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (options.ClientFactory == null)
            {
                throw new ArgumentNullException(nameof(options.ClientFactory));
            }

            disposeContextAction = options.DisposeContextAction;
            var client = options.ClientFactory.CreateClient(options.Url);

            Database = client.GetDatabase(options.Url.DatabaseName);

            foreach (var collectionOptions in options.Collections)
            {
                var collectionContext = collectionOptions.BuildContext();

                collectionContext.Initialize(collectionOptions.CollectionName, this);

                var index = collections.Count;
                collections.Add(collectionContext);
                collectionDocumentTypes.Add(collectionContext.DocumentType, index);
                collectionNames.Add(collectionContext.CollectionName.ToLower(), index);
            }
        }
        private MongoDbContextOptions BuildOptions(IServiceProvider provider)
        {
            if (ConnectionString == null)
            {
                throw new InvalidOperationException($"Not set {nameof(ConnectionString)} value.");
            }

            if (DatabaseName == null)
            {
                throw new InvalidOperationException($"Not set {nameof(DatabaseName)} value.");
            }

            var mongoUrlBuilder = new MongoUrlBuilder(ConnectionString)
            {
                DatabaseName = DatabaseName
            };

            var mongoUrl      = mongoUrlBuilder.ToMongoUrl();
            var clientFactory = provider.GetService <IMongoDbClientFactory>();

            if (clientFactory == null)
            {
                clientFactory = MongoDbClientFactory.Instance;
            }

            var options = new MongoDbContextOptions
            {
                Url           = mongoUrl,
                ClientFactory = clientFactory
            };

            options.Collections.AddRange(collections);

            return(options);
        }