简体   繁体   中英

Using MongoDB as Service in ASP.NET Core Blazor

So I have the following MongoDBService that I have created:

public class MongoDBService
{
    private const String CONNECTION_STRING = "mongodb://localhost:27017";
    private const String DATABASE_NAME = "TestingTesting";
    private readonly MongoClient _Client;

    public MongoDBService()
    {
        _Client = new MongoClient(CONNECTION_STRING);
    }

    public IMongoCollection<T> GetCollection<T>()
    {
        return _Client.GetDatabase(DATABASE_NAME).GetCollection<T>(typeof(T).Name);
    }
}

I have set MongoDBService as a service in my asp.net core Startup.cs:

services.AddSingleton<MongoDBService>();

I am then trying to use the service by injecting it into the .razor page:

@inject Project.Services.MongoDBService

I am also initiating an instance of my MongoDBService:

Project.Services.MongoDBService mongo = new Services.MongoDBService();

But when I then try to use it, I get a red squiggly line under the FindAsync() method:

async Task GetAllClocks()
{
    MongoDB.Driver.FilterDefinition<Project.Data.Clock> filter = MongoDB.Driver.Builders<Project.Data.Clock>.Filter.Empty;

    MongoDB.Driver.IMongoCollection<Project.Data.Clock> cursor = await mongo.GetCollection<Project.Data.Clock>().FindAsync(filter);
}

The error is:

CS0411: The type arguments for method 'IMongoCollection.FindAsync(FilterDefinition, FindOptions<Clock, TProjection>, CancellationToken)' cannot be inferred from the usage. Try specifying the type

I've been Googling for a while and while it sounds like I'm leaving the compiler to decide what type to use, I'm sure I am explicitly specifying the Project.Data.Clock type. Absolutely stumped. Any ideas?

FindOptions needs two type parameters, and you are only supplying one. If you wish to return a Clock object, try FindOptions<Clock, Clock> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM