Stan
Stan

Reputation: 26501

Make class return different type

I want to create a simple DbContext class to avoid repetitive code in my repositories. The problem is that I don't know how to make it initialize/configure itself in constructor and then return itself. I only know how to assign additional property in that class and then call it.

I'm not sure how to properly articulate my problem so feel free to edit, however I think it will be very clear if you look at the code.

As you can see I'm calling .GetDatabase on every query, what I want is to remove .GetDatabase and make _db return what .GetDatabase is returning.

DbContext

public class DbContext
{
    public DbContext()
    {
        var client = new MongoClient("mongodb://localhost");
        var server = client.GetServer();
        this.GetDatabase = server.GetDatabase("test");
    }

    public MongoDatabase GetDatabase { get; private set; }
}

Repository

public class AdministratorRepository
{
    private readonly DbContext _db = new DbContext();

    public Administrator GetByUsername(string username)
    {
        return _db.GetDatabase // I want to remove this .GetDatabase and make my _db itself return database
            .GetCollection<Administrator>("administrators")
            .FindOne(Query<Administrator>.EQ(x => x.Username, username));
    }
}

Upvotes: 1

Views: 114

Answers (2)

haim770
haim770

Reputation: 49095

Assuming your DbContext is only a wrapper you're using to initialize MongoDatabase, try this:

public class DbContext
{
    public static MongoDatabase GetDatabase()
    {
        var client = new MongoClient("mongodb://localhost");
        var server = client.GetServer();

        return server.GetDatabase("test");
    }
}

Then in client code:

private readonly MongoDatabase _db = DbContext.GetDatabase();

Also, you better pass the connection-string and database name as a parameter and avoid hard-coding it in the method.

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

You need to add one method to the DbContext class:

public ?? GetCollection<T>(string collection)
{
    return _db.GetCollection<T>(collection);
}

I think the type is MongoCollection, but I'm not certain on that. Now you can do this:

return _db.GetCollection<Administrator>("administrators")
        .FindOne(Query<Administrator>.EQ(x => x.Username, username));

Upvotes: 2

Related Questions